Could someone explain why the following code behaves differently if the 3 first printf calls are there or not ?
#include <stdlib.h>
#include <stdio.h>
int main(){
int a = 1;
int b = 2;
int c = 3;
int* a_ptr = &a;
// comment out the following 3 lines
printf(" &a : %p\n", &a);
printf(" &b : %p\n", &b);
printf(" &c : %p\n", &c);
printf("*(a_ptr) : %d\n", *(a_ptr));
printf("*(a_ptr-1) : %d\n", *(a_ptr-1));
printf("*(a_ptr-2) : %d\n", *(a_ptr-2));
I was playing around to learn how variables are being stacked in memory depending on the order of declaration. By printing the addresses, I see they are 1 int size apart if they are declared after each other. After printing the addreses, I just subtract 1 and 2 from the address of a and dereference it. When I print it, it shows what i'd expect, the values of a, b and c. BUT, if i do not print the addresses before, I just get a=1, while b and c seem random to me. What is going on here ? Do you get the same behaviour on your machine ?
// without printing the addresses
*(a_ptr) : 1
*(a_ptr-1) : 4200880
*(a_ptr-2) : 6422400
// with printing
&a : 0061FF18
&b : 0061FF14
&c : 0061FF10
*(a_ptr) : 1
*(a_ptr-1) : 2
*(a_ptr-2) : 3