pointers - Understanding addresses in C -
for structure splab:
int main() { int a; struct splab *s1; int b; printf("%x\n",&a); printf("%x\n",&b); return 0; } i think should in second print: bfc251e8 - 8 (i.e. account space occupied s1).
instead, got:
bfc251e8 bfc251ec why?
it's not order of variables. never use s1 , compiler can (and may) optimize away , not allocate space on stack.
here if try print addresses of a , b, do:
ffeb7448 (&a) ffeb7444 (&b) i.e. 4 bytes difference.
here if try print address of s1 (and therefore end using declaration s1):
ffe109cc (&a) ffe109c8 (&s1) ffe109c4 (&b) you can see in fact lie in between a , b time (and need not always, other answers point out), , a , b separated 8 bytes instead of 4.
another related point has alignment:
for example:
struct foo { int a; char b; }; while struct looks might 5 bytes wide on machine 4 byte integers, compiler says, sizeof (struct foo) == 8.
this foo aligned @ 8 byte boundaries (this includes use of struct foo local variables).
e.g.
int bar (void) { struct foo a; struct foo b; /* work. */ } here, a , b separated 8 bytes on machine's compiler, though each foo ever uses 5 bytes.
all goes show is: never assume related widths, alignment, relative position, etc. when writing code.
Comments
Post a Comment