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 5 of 9.
Aakash Gupta said:
1 decade ago
In borland and turbo c++ it gives the error: Cannot Convert "int*" to "char*".
Mohit said:
1 decade ago
There is a warning of converting int* to char* but, there is no error. Actually we do not follow such coding practice but for the question answer is 2, 0.
Balu said:
1 decade ago
Assume ,
arr[0] = 1000.
arr[1] = 1004.
arr[2] = 1008.
now,
p=arr; i.e p=1000.
p = (char*)((int*)(p));
At this statement character pointer p 1st typecasted to integer pointer and again typecasted to character pointer.
printf("%d, ", *p);-prints value 2.
As memory representation for little endian (lowest byte will stored 1st).
00000010 00000000 00000000 00000000
p = (int*)(p+1);-in this statement p which is char pointer is incremented by one so it is pointing at location 1001.
printf("%d", *p);-prints value 0 because at memory location 1001 value 0 is stored (according to little endian ).
arr[0] = 1000.
arr[1] = 1004.
arr[2] = 1008.
now,
p=arr; i.e p=1000.
p = (char*)((int*)(p));
At this statement character pointer p 1st typecasted to integer pointer and again typecasted to character pointer.
printf("%d, ", *p);-prints value 2.
As memory representation for little endian (lowest byte will stored 1st).
00000010 00000000 00000000 00000000
p = (int*)(p+1);-in this statement p which is char pointer is incremented by one so it is pointing at location 1001.
printf("%d", *p);-prints value 0 because at memory location 1001 value 0 is stored (according to little endian ).
Manishj said:
1 decade ago
It gives warning as incompatible pointer type.
Answer 2, 0 is correct.
It doesn't show errors.
Answer 2, 0 is correct.
It doesn't show errors.
Varni said:
1 decade ago
Why not upper byte of 2 not considered here ? (00000000).
Is it put at the end of the array ?
Is it put at the end of the array ?
Vaibhav said:
1 decade ago
p = (int*)(p+1) ; what it does actually ?
Sanjoy said:
1 decade ago
What is type casted?
Garvita said:
1 decade ago
Why we type casted p again to char?
p=(char*)((int*)(p));
p=(char*)((int*)(p));
Raghav said:
1 decade ago
(char*)((int*)(p))
Could someone explain this?
Could someone explain this?
Ankita said:
1 decade ago
What is this endian method?
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers