Razor21 Razor21 - 3 months ago 7
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:

#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;
}


Options:

A. 2, 3

B. 2, 0

C. 2, Garbage value

D. 0, 0

According to the textbook the answer is
B
, but I'm confused - can someone 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.

Comments