Discussion
What is the output of the following program ?
#include<stdio.h>
void f(int *p, int *q) {
p=q;
*p=2;
}
int i=0, j=1;
int main(void){
f(&i, &j);
printf("%d %d\n", i, j);
}
Answer: D
The program prints 0 2.
C passes arguments by value, so p and q are local copies of the addresses &i and &j. Walk through f:
p=q;changes only the local copy p, which now holds &j. The variable i is untouched.*p=2;writes 2 through p, that is into j.
Back in main, i is still 0 and j is now 2, so printf prints 0 2. '2 1' is what you would get if *p=2 still wrote to i; '2 2' assumes p=q changed main's pointer; '0 1' ignores the write through p altogether.
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