Razor21 Razor21 - 3 months ago 17
C Question

Explain the output of pointers code

#include<stdio.h>

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

The correct ans according to my textbook is (b). Can someone please explain why ?

Answer

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.