Discussion
What will be the output of the following C code?
#include <stdio.h>
void main()
{
int x = 4;
int *p = &x;
int *k = p++;
int r = p - k;
printf("%d", r);
}
Answer: C
Correct answer: 1
Pointer arithmetic is in units of the pointed-to type, not in bytes. p++ advances p by one int, and k keeps the address p held beforehand, since ++ is postfix.
The difference of two pointers is likewise expressed in elements:
\[ p - k = 1 \]
The distractor 4 is the difference in bytes on a machine with four-byte ints, which is what a beginner expects; the language deliberately hides that scaling so that pointer arithmetic works the same way for every 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