Noober Noober - 2 months ago 7x
C Question

Passing arguments by reference and Pointers in c

I have the following code-

#include <stdio.h>

void changeData(int * ax,int * ay)

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


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


Since I am doing
, so
, then

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


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.