C Programming - Pointers - Discussion

Discussion Forum : Pointers - Find Output of Program (Q.No. 13)
13.
What will be the output of the program?
#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;
}
2, 3
2, 0
2, Garbage value
0, 0
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
87 comments Page 3 of 9.

Shashank said:   1 decade ago
Please tell me how this program will execute.

Madhuri said:   1 decade ago
Good explanation viraj.

Vijay Singh said:   1 decade ago
It's give error in turbo c3
p = arr; \\ can not convert "int *" to "char *"
p = (int*)(p+1); \\ can not convert "int *" to "char *"

SHAHIDNX said:   1 decade ago
First it will perform outer typecast then it will perform inner typecast.

And in second printf since pointer type is char so it point to 1byte data. Hence it will fetch the first byte of value 2 and p+1 point to second byte of value 2.

So it is zero (2=0000000000000010).

Puru said:   1 decade ago
@viraj accepted your idea. its the same

Puru said:   1 decade ago
p = (char*)((int*)(p));
// till now the pointer p is type casted to store the variable of type character.

printf("%d, ", *p); // %d means integer value so value at first address i.e. 2 will be printed.

p = (int*)(p+1); // here p is still of type character as type casted in step 1 so p(i.e address) and plus 1 will increase only by one byte so

as per viraj suggested

Assuming that integer requires 2 bytes of storage
the integer array will be stored in memory as


value 2 3 4
address 00000010 00000000 00000011 00000000 00000100 00000000
pointer p+1


so p+1 points to that location which is unfilled as during intialization 2,3,4 were stored in variable of type integer(2 bytes).

so p+1 will point to 00000000.

(int*)p+1 // p+1 is type casted again to integer

printf("%d", *p); // this will print 0 as output as by default integer contains 0 as value.

Swati said:   1 decade ago
It gives error "cannot convert 'int*' to 'char*'" in both lines

p=arr;
p=(int*)(p+1);

Abhishek.e.k said:   1 decade ago
p = (char*)((int*)(p));
even without this line program will run fine

Vivek said:   1 decade ago
char p stored in int type arr. which is not possible without conversion.

Vanni said:   1 decade ago
I didn't get this one can anyone explain me?


Post your comments here:

Your comments will be displayed after verification.