I have the following code:
int** x;
// Add 4 int pointers to x - code ommitted
// Pop the first element
int* a = x[0];
memmove(&x[0], &x[1], sizeof(int*) * 3);
x = realloc(x, sizeof(int*) * 3);
// Some code that uses 'a' - ommitted
As per my understanding a
is now pointing at the first location x
points to. But that memory location now actually contains the data that was previously on x[1]
due to the memmove
.
Looking at how this code is used, it seems that a
should actually point to the value that was previously on x[0]
. My question is, how is it possible for a
to contain that previous value if that memory location has been now replaced by what was in x[1]
?
a
is a variable on the stack to which you assigned the value of x[0]
before you changed (by memmove) the value of x[0]
. Hence, a will retain the value of x[0] and the array x will have the original x[1],x[2],x[3]
stored at x[0],x[1],x[2]
So basically a acts as a local variable which is a copy of the data at x[0]. The said data is an integer pointer but could be anything else.