- Get link
- X
- Other Apps
GATE2025_CS1_Q34
The output of the given C program is ______. (Answer in integer)
#include
void foo(int *p, int x){
*p = x;
}
int main(){
int *z;
int a = 20, b = 25;
z = &a;
foo(z, b);
printf("%d", a);
return 0;
}
✅ Final Answer:
The correct output of the program is 25.
🔹 Short Answer:
The program demonstrates the concept of "pass-by-reference" using pointers. The pointer z is set to the address of variable a. This address is passed to the function foo. Inside foo, the statement *p = x dereferences the pointer to access the original variable a and changes its value to 25. Therefore, when printf is called in main, it prints the modified value of a, which is 25.
🔸 Long Answer:
To understand the program's output, let's trace its execution step-by-step and visualize the memory.
Execution Trace:
int main()execution begins.int a = 20, b = 25;
Two integer variables are declared and initialized.aholds the value 20, andbholds the value 25.int *z;
An integer pointerzis declared. It currently points to nothing (or holds a garbage value).z = &a;
The pointerzis assigned the memory address of variablea. Now,z"points to"a. Any operation using*zwill directly affect the variablea.foo(z, b);
The program calls the functionfoo.- The value of
z(which is the address ofa) is passed to the pointer parameterp. So, insidefoo,palso points toa. - The value of
b(which is 25) is passed to the integer parameterx. This is a pass-by-value, soxinside _foo_ is a copy ofb.
- The value of
- Inside
foo(int *p, int x):- The statement
*p = x;is executed. *pis the dereferencing operator. It means "the value at the address stored inp". Sincepholds the address ofa,*prefers to the variableaitself.- The statement effectively becomes: "Set the value of
ato the value ofx". - Since
xis 25, the value ofain themainfunction is changed from 20 to 25.
- The statement
printf("%d", a);
The functionfooreturns, and the program continues inmain. Theprintfstatement prints the current value of the variablea. Sinceawas modified by thefoofunction, its current value is 25.
The final output printed to the console is 25.
Bibliography:
- Kernighan, B. W., & Ritchie, D. M. (1988). The C Programming Language. Prentice Hall. (Chapter 5: Pointers and Arrays).
- Kernighan, B. W., & Ritchie, D. M. (1988). The C Programming Language. Prentice Hall. (Chapter 5: Pointers and Arrays).
Ask your doubts in comment form our GURUJEE will reply ASAP, click notify me button so that you get notified on reply.
- Get link
- X
- Other Apps
Comments
Post a Comment
Ask you doubt here