I've been trying to understand pointers, in particular the pointer[i] notation which is the equivalent of *(pointer + i), ie dereferencing the value at the next address, so if its an int pointer than the next 4 byte address. And I tried running the following code below:
#include <stdio.h>
int main(void){
int x = 10;
int y = 20;
int* z = &y;
printf("address of x: %u ", &x);
printf("address of y: %u", &y);
printf("value at address: %u \n", *(z+1));
}
I noticed that 'y' was stored 4 bytes before 'x', and thought that i would be able to return the value stored at x's address by z[1] or *(z+1), which worked fine.
However when I removed the first 2 printf's, I ended up with the address being outputted instead of the actual value (10), here is the code for this case:
#include <stdio.h>
int main(void){
int x = 10;
int y = 20;
int* z = &y;
printf("value at address: %u \n", *(z+1));
}
I am assuming that *(z+1) is no longer referring to the same area of memory as the variable 'x' , but I am confused as to why this change in the code caused this.
Initially i thought it was one off, so I tried this multiple times and got the same results each time.
Whats even more confusing is how the code works as expected in both cases on ubuntu and macos, but not on windows.
Any help regarding this would be great, thanks.