How does the following pointer diagram work out in C?
Given the data shown above from a 16-bit system, with integer x, unsigned integer y, and integer z, what will the following code snippet print out?
@oldrin.bataku
int *p = &x; /* p points to the value 0x0000 at 0x0002 */ printf("%d\n", *p); /* print the value p points to (0) */ p++; /* p now points to the address 0x0004 since sizeof(int) = 2 here */ x = (int) p; /* now x's value is that address, 0x0004 */ printf("%d\n", x); /* print the value of x (0x0004) */ printf("%d\n", *p); /* p still points to the value in y at 0x0004, which is 0x0005 */ printf("%d\n", *(&(*p))); /* *p is an alias for y, so &(*p) is equivalent to p, and then *(&(*p)) gives the value in y, which is still 0x0005 */ printf("%d\n", *(p-1) + 1); /* so p-1 gives the address 0x0002 again, so p-1 points to x, meaning *(p-1) gives the value in x (0x0004) and then +1 gives 0x0005 */
Join our real-time social learning platform and learn together with your friends!