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 1 of 9.
Badareenath said:
2 decades ago
Can anybody explain this please ?
Ravi said:
2 decades ago
p=arr;//here p is a character pointer. we should not assign int array base address...
DRukus said:
2 decades ago
p is declared as a char pointer but arr is an integer array
the assignment p = arr produces a compile-time error.
the assignment p = arr produces a compile-time error.
Rajadurai said:
2 decades ago
The answer is correct. We can convert int pointer to char pointer and viz versa. *p is apoint to first variable. *p+1 points the next array, so the answer is zero.
Sundar said:
1 decade ago
The char pointer only stores the first byte address of integer. So while increment the pointer the next value is to be printed as 0.
Prateek said:
1 decade ago
p is a char. pointer and it is assigned to complete address of arr array. so when we write (ar+1) it take address next beyond arr array. which having value 0 of defined pointer array.
Sai said:
1 decade ago
Please explain about
p = (int*)(p+1);
printf("%d", *p);
p = (int*)(p+1);
printf("%d", *p);
Purushotham said:
1 decade ago
p = arr;
causes compile time error
causes compile time error
Viraj said:
1 decade ago
The answer is correct. Assuming that integer requires 2 bytes of storage
the integer array will be stored in memory as
00000010 00000000 00000011 00000000 00000100 00000000
This is because little-endian method is used to store bytes in memory i.e. least significant bytes are stored first.
When a character pointer is incremented by it points to the next byte. Hence the answer.
the integer array will be stored in memory as
00000010 00000000 00000011 00000000 00000100 00000000
This is because little-endian method is used to store bytes in memory i.e. least significant bytes are stored first.
When a character pointer is incremented by it points to the next byte. Hence the answer.
(1)
Nitin said:
1 decade ago
Well explained Viraj.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers