Get element in pointer to array

Following learning about pointers and now simple arrays I’m curious how pointers to arrays may work. I tried all morning playing around and I don’t know even the general concept is.

As a starting point I setup an array and read an element from it and also stored a pointer to the array (arrayPtr). My question, how can I use the pointer “arrayPtr” now?

I’m using the C API builder so I thought I could pass it in to LLVMBuildIntCast2 but the results were wrong. Do you need to do a bit cast or something? Totally confused and there’s no examples I can find of this online.

@myArray = global [5 x i32] [i32 10, i32 20, i32 30, i32 40, i32 50]
@arrayPtr = global ptr null

define i8 @main() {
entry:
  store ptr @myArray, ptr @arrayPtr, align 8
  %element = load i32, ptr getelementptr inbounds ([5 x i32], ptr @myArray, i32 0, i32 1), align 4
  ret i8 0
}

@myArray is a pointer to the array. @arrayPtr is a pointer to the pointer to the array.

You need to first load ptr from @arrayPtr to get the pointer to the array. Then you need to use getelementptr to go the pointer to the array element you want (as your example does). Then you need to load i32 from that pointer to get the actual array element.

1 Like

This may help The Often Misunderstood GEP Instruction — LLVM 17.0.0git documentation

1 Like

oh man I really misunderstood this. Is it a pointer because the array is global or does this apply to stack arrays created from alloca also? I thought if I did load on @myArray it would load the entire array into memory, in this case i32x5 even though I only need to load a single element.

load always loads a value from a pointer. If @myArray was not a pointer there would be no way to load it. This is why all global values are pointers, even though they may not look like ones. E.g. @main is also a pointer.
alloca always produces a pointer to the specified type.

1 Like

That article you sent is helping thanks.

btw I’ve read around that people are compiling c programs and getting back LLVM IR somehow. Is there an option for clang or something I can use for this? That would probably be helpful to do when I get stuck.

That article you sent is helping thanks.

It is really simple if you keep in mind that getelementptr is just a pointer arithmetic. It is like add or sub, but is designed specifically for pointers.

Is there an option for clang or something I can use for this?

It is -emit-llvm. Make sure you add -S too, otherwise it will produce IR in binary format.

1 Like