Discussion
What is the output of this C code?
#include <stdio.h>
void foo(int*);
int main()
{
int i = 10, *p = &i;
foo(p++);
}
void foo(int *p)
{
printf("%d\n", *p);
}
Answer: A
Correct answer: 10
p++ is a post-increment, so the value passed to foo is p as it was - the address of i - and only afterwards does p advance.
foo therefore dereferences a valid pointer and prints 10. The increment leaves p pointing one past i, which is never used, so no harm follows. Had the pre-increment ++p been written, the pointer passed would have been one past the object and the dereference undefined.
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