Discussion
What is the output of this C code?
#include <stdio.h>
int main()
{
int i = 97, *p = &i;
foo(&i);
printf("%d ", *p);
}
void foo(int *p)
{
int j = 2;
p = &j;
printf("%d ", *p);
}
Answer: A
Correct answer: 2 97
foo receives a copy of the pointer. Assigning p = &j inside it changes only that copy, so foo prints 2 and the caller's pointer is untouched.
Back in main, p still points at i, and 97 is printed. C passes everything by value, pointers included: to let a function change the caller's pointer it must be given the address of that pointer, which is what the companion question does with int **.
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