MrAdityaAlok
MrAdityaAlok

Reputation: 97

Why difference between int and pointer address is always 12?

Code


#include <stdio.h>

int main(void) {
  int x = 4;
  int *ptr = &x;
  printf("Address of x      : %p\n", &x);
  printf("Address of ptr    : %p\n", &ptr);
}

Output :

Address of x      : 0x7fc5492fac
Address of ptr    : 0x7fc5492fa0

When I convert hex to decimal and subtract :

Difference is of 12(always).

Question

My question is, if both are stored in contiguous memory(which should be the case as difference is always of 12 and as the difference is positive ptr must come before x) and &ptr is the address of pointer then why the difference is 12?

I thought it must be 4 as x is of 4 bytes(on my system) and exactly before this is ptr.

Please correct me, if I'm wrong.

Upvotes: 1

Views: 190

Answers (1)

dbush
dbush

Reputation: 224362

The placement of variables in memory is entirely up to the implementation. There is no requirement that they be in any particular order or that they be placed any particular distance apart.

For example, on my machine using gcc if I compile with -O0 I see the same result as you, with ptr being first and x being 12 after that, but if I compile with -O3 then x is first and ptr is 16 after that.

Upvotes: 4

Related Questions