Razor21 Razor21 - 1 year ago 69
C Question

Why is this the output of the pointer?

My textbook has a question that asks what will the output be of the following code snippet:


int main()
int arr[3] = {2, 3, 4};
char *p;
p = arr;
p = (char*)((int*)(p));
printf("%d, ", *p);
p = (int*)(p+1);
printf("%d", *p);
return 0;


A. 2, 3

B. 2, 0

C. 2, Garbage value

D. 0, 0

According to the textbook the answer is
, but I'm confused - can someone explain why?

Answer Source

Warning: Some of this is rather simplified.

It's about memory layout. When you define arr, it is an array of int and looks like this in memory:

2, 3, 4

But each int is (or rather may be, C is kinda platform dependent.) eight chars long. So when viewed as an array of char it looks like this:

2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0

As p is of type char *, adding one to p advances your pointer by one as if in the second perspective. Therefore you get this output.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download