Discussion
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;
}
Answer: B
Correct answer: 2, 0
p is a char *, so dereferencing it reads a single byte. The first element of the array holds 2, and on a little-endian machine the low-order byte comes first, so *p is 2.
After p+1, the pointer addresses the second byte of that same integer - not the next element, since char arithmetic advances by one byte. For the value 2 in a four-byte int, that byte is zero. The casts are decorative; what matters is that arithmetic is scaled by the pointer's type.
No comment is present. Be the first to comment.
Loading…
Post your comment
Please log in or register to post a comment.
Examination Categories
- SSC Exams
- Banking Exams
- Teaching Exams
- Civil Services Exams
- Railways Exams
- Engineering Recruitment Exams
- Defence Exams
- State Government Exams
- Police Exams
- Insurance Exams
- Nursing Exams
- Other Government Exams
- NRA CET
- PG Entrance Exams
- Campus Placement
- MBA Entrance Exams
- CUET and UG Entrance
- Judiciary Exams
- Regulatory Body Exams
- Software Development