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 2 of 9.

Dilbagh said:   1 decade ago
Viraj you are excellent.

Adi said:   1 decade ago
Well done viraj.

Rahul p said:   1 decade ago
@viraj

Your answer is correct. But here integer requires 4 bytes of storage

Hence, when

p = (int*)(p+4); It will print next element of arr which is 3.

&

p = (int*)(p+8);It will print next element of arr which is 4.

Pankaj said:   1 decade ago
I tried to run this program but it gives compiletime error:
"suspicious pointer conversion" for below lines
p = arr;
p = (int*)(p+1);

Lucky said:   1 decade ago
p = (char*)((int*)(p)); means?

Abhi said:   1 decade ago
@ pankaj

p is char type pointer and v cant assign int type arr to it . so ... it says suspicious ptr and in the next line if v dint do any type casting thn also it ill execute . and the line p=(char*)((int*)(p))); in the sense v r type castng the p to int and thn whole to char type.
since char has 1 byte it stores oly 1st byte tht is 2 and wen v increment it gives value 0

Ankur said:   1 decade ago
@pankaj.

Dude run it on turbo c it won't give you an error.

Akhil said:   1 decade ago
Thank you for such a nice discussion... :)

Nahak said:   1 decade ago
Nice one viraj. Really helpful.

Himanshu batra said:   1 decade ago
Happy Budday viraj. Great job.


Post your comments here:

Your comments will be displayed after verification.