Ayse Ayse - 1 year ago 71
C Question

Assigning int value to an address

I thought the following codes were correct but it is not working.

int x, *ra;
&ra = x;


int x, ra;
&ra = x;

Please help me if both of these code snippets are correct. If not, what errors do you see in them?

Thanks in advance.

Answer Source

Your both expressions are incorrect, It should be:

int x, *ra;
ra  = &x;  // pointer variable assigning address of x

& is ampersand is an address of operator (in unary syntax), using & you can assign address of variable x into pointer variable ra.

Moreover as you question title suggests: Assigning int value to an address.

ra is a pointer contains address of variable x so you can assigning an new value to x via ra

*ra = 20; 

Here * before pointer variable (in unary syntax) is deference operator gives value at the address.

Because you have also tagged question to so I think you are confuse with reference variable declaration, that is:

int x = 10;
int &ra = x; // reference at time of declaration 

Accordingly in case of reference variable, if you wants to assign a new value to x its very simple in syntax as we do with value variable:

ra = 20;

(notice even ra is reference variable we assigns to x without & or * still change reflects, this is the benefit of reference variable: simple to use capable as pointers!)

Remember reference binding given at the time of declaration and it can't be change where pointer variable can point to new variable latter in program.

In C we only have pointer and value variable, whereas in C++ we have pointer, reference and value variable. In my linked answer I tried to explain differences between pointer and reference variable.

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