Rog Matthews
Rog Matthews

Reputation: 3247

Problems in the Address Assignment

In this C code i have tried to assign pointer addresses of one variable to other with some changes and then back again.

#include<stdio.h>
void change(int *x)
{
    int *z;
    z=x+5;
    printf("%u\n",z);
    x=z;
    printf("%u\n",x);
}
int main()
{
    int *p;
    int y=2;
    p=&y;
    printf("%u\n",p);
    change(p);
    printf("%u\n",p);
    return 0;
}

Output is:

2280640
2280660
2280660
2280640

Can somebody please explain that why is the last line of the output 2280640. I think that it should be 2280660.

Upvotes: 2

Views: 81

Answers (1)

Alok Save
Alok Save

Reputation: 206518

You are passing the pointer by value. A copy of the pointer pgets passed to the function change() and not the pointer pitself.

To be able to modify p inside the function you will have to pass it by reference.

void change(int **x) 

and call it as

 change(&p);

and inside change do the assignment as

 *x = z;

Upvotes: 7

Related Questions