Let’s say we have an array defined as a global variable.
int array[] = {16, 25, 36, 49, 64};
If this is compiled as a shared library, compiler will produce a binary with a symbol “array” pointing to the location in memory of the array.
Is it possible to add a global variable that will represent a memory location that is inside of the array.
int elem;
Can it be some how made that elem represents the same location as array[2]? Is that even possible with just C?
EDIT:
Can it be done without involving pointers? I am interested into making elem being the location in memory at witch array[2] resides. With int* elem = &array[2] memory is set aside for a pointer and elem becomes a symbol for that pointer, and then the memory adress of array[2] is put in there. I would like that elem becomes a symbol for a location of array[2], so that assert(elem == array[2]) would pass always. Like an identity in math (≡).
Does anybody know is the thing I am interested in possible in plain C, or only in assembly.
This is impossible in plain C without using a pointer.
You can, however, use some linker trickery to achieve this (beware that this is not portable and very, very hacky): Get your default linker script from
ld -verboseand edit it to include something likeelem = (array) + 4 * 2;, then compile with-Wl,-Tyour_script.ld.elemshould now occupy the same memory address asarray+ 8 Bytes (which isarray[2]assumingsizeof(int) == 4):