Noober Noober - 4 months ago 10
C Question

Passing arguments by reference and Pointers in c

I have the following code-

#include <stdio.h>

void changeData(int * ax,int * ay)
{
ax=ay;
*ay=0;
*ax=*ax+*ay;
}

int main()
{
int x=13;
int y=21;

changeData(&x,&y);

printf("x: %d\n",x );

}


Since I am doing
ax=ay
, so
ax=21
, then
*ax=21+0=21

So, the answer printed should be
21
. But I get
x=13
as output. Why is it so?

Answer

C does not support pass by reference, strictly speaking. You can pass the value of a variables address and dereference that value.

Your function changes the local variable ax to hold the same value as ay, namely the address of y in main. At this point, no variable in this function contains the address of x in main so it cannot be modified.

The next line in changeData dereferences ay and sets the value at that address (i.e. y in main) to 0. The third line then dereferences ax which currently contains the address of y, not x, and sets it to the value ax points to (y in main which contains 0) plus the value ay points to (again, y in main which is 0).

When the function returns, x is unchanged and thus the printf outputs 13. If you were to print y as well, you would see it is 0.