What does the following program print?void f(int *p, int *q) { p = q; *p = 2;}int i = 0, j = 1;int main() { f(&i, &j); printf("%d %d \n", i, j); getchar(); return 0;}Options2 22 10 10 2
Question
What does the following program print?void f(int *p, int *q) { p = q; *p = 2;}int i = 0, j = 1;int main() { f(&i, &j); printf("%d %d \n", i, j); getchar(); return 0;}Options2 22 10 10 2
Solution
The program prints "0 2".
Here's the step-by-step explanation:
-
The program starts with the declaration of two integer variables
iandj, withiinitialized to0andjto1. -
The
mainfunction is then called. Insidemain, the functionfis called with the addresses ofiandjas arguments. -
Inside function
f, the pointerpis assigned the value ofq, which is the address ofj. Then, the value at the address stored inp(which is now the address ofj) is set to2. This changes the value ofjto2, butiremains0becausepwas reassigned toqbefore the value change, soiwas not affected. -
After function
fis done, the program returns tomainand proceeds to theprintfstatement, which prints the values ofiandj. Sinceiis still0andjis now2, the output is "0 2". -
The
getchar()function is then called, which waits for a character input from the user. This is often used in console programs to prevent the console from closing immediately after the program is run. -
Finally, the program returns
0and ends.
Similar Questions
What does the following program print?#include <stdio.h>int main() { int arr[5] = {1, 2, 3, 4, 5}; int *p = arr; p++; printf("%d\n", *p); return 0;}
What will be the output of the following code?int main() { int a = 10; int *p = &a; *p = 20; printf("%d\n", a); return 0;}
What is the output of the following C code:#include <stdio.h>void fun(int **p);int main(){ int a[3][4] = {1, 2, 3, 4, 4, 3, 2, 8, 7, 8, 9, 0}; int *ptr; ptr = &a[0][0]; fun(&ptr); return 0;}void fun(int **p){ printf("%d\n", **p);}1234
What does the following C-statement declare?int ( * f) (int * ) ;a.A function that takes an integer pointer as argument and returns a function pointerb.A pointer to a function that takes an integer pointer as argument and returns an integer.c.A function that takes an integer pointer as argument and returns an integerd.A function that takes an integer as argument and returns an integer pointer
What does this code print?* print_something - function to print something** Return: Always 0**/int print_something(int num){ int i, j; for (i = 0; i < num + 1; i++) { for (j = 0; j < num + 1; j++) { printf("%d", i * j); if (j < num) { printf(", "); } } printf("\n"); } return (0);}
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.