简体   繁体   中英

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:

  • 0x7fc5492fac: 548770754476
  • 0x7fc5492fa0: 548770754464

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM