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;
}
Discussion:
87 comments Page 6 of 9.
Akhil said:
1 decade ago
Thank you for such a nice discussion... :)
Ankur said:
1 decade ago
@pankaj.
Dude run it on turbo c it won't give you an error.
Dude run it on turbo c it won't give you an error.
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
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
Lucky said:
1 decade ago
p = (char*)((int*)(p)); means?
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);
"suspicious pointer conversion" for below lines
p = arr;
p = (int*)(p+1);
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).
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).
Adi said:
1 decade ago
Well done viraj.
Dilbagh said:
1 decade ago
Viraj you are excellent.
Nitin said:
1 decade ago
Well explained Viraj.
Purushotham said:
1 decade ago
p = arr;
causes compile time error
causes compile time error
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers