Jasmine Jasmine - 1 year ago 85
C Question

Determining the output with pointers

I need help understanding some of the outputs of the code below. (This is just a sample question for a midterm, not homework).

#include <stdio.h>
void figure_me_out(int* a, int b, int c, int* d);

int main(void) {
int var1 = 1, var2 = 10, var3 = 15, var4 = 20;
figure_me_out(&var1, var2, var3, &var4);
printf("%d, %d, %d, %d\n", var1, var2, var3, var4);
return 0;

void figure_me_out(int* a, int b, int c, int* d) {
c = b;
b = *d;
*a = 222;
*d = 100;
a = d;
*a = c;


222, 10, 15, 10

When I went through the code, I got 10, 10, 15, 100. This was my logic:

c = 10 ---> c was passed by value, so c does not change for printf

b = 20 ---> same reason as above

*a = 222 ---> this dereferences a and gives it the value of 222. Since var a was passed by reference, it changes the original value.

*d = 100 ---> same reason as above

(this part is where I get confused)
a = 100 ---> I'm thinking that since d was changed to 100, that means a is assigned what d equals now, which is 100.

*a = 10 ---> changing the value of a to 10

I know that the function did not alter the original values of b (var2) and c (var3) since they were passed by value but it altered the rest. So I'm confused as to why var1 prints as 222 and var4 prints as 10.

Answer Source

Its simple I think, Lets go step by step:

void figure_me_out(int* a, int b, int c, int* d) 
 c = b;    // c = 10
 b = *d;   // b = 20
 *a = 222; // *a = 222 : Value at address a is changed to 222
 *d = 100; // *d = 100 : Value at address d is changed to 100
 a = d;    // a = d: Change address of local pointer variable a to d. 
 *a = c;   // Changing value of address a which is same as address d to 10

In step 3 you have changed original value at address a which you have passed from main function. In step 5 you are changing passed address from main to local variable a in function. After doing a = d, local variable having address is changed to address of d. Now anything you do with this address will get effected at address location of d In step 6 you have changed the value of d to 10.

So final answer coming is 222, 10, 15, 10

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download