I thought the following codes were correct but it is not working.
int x, *ra;
&ra = x;
and
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?
Both of your 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 your question title suggests: Assigning int value to an address
.
ra
is a pointer contains address of variable x
so you can assign a new value to x
via ra
*ra = 20;
Here, the *
before pointer variable (in unary syntax) is the deference operator which gives the value stored at the address.
Because you have also tagged question to c++ 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 the reference variable, if you want to assign a new value to x
it is very simply in syntax as we do with value variable:
ra = 20;
(notice even ra
is reference variable we assign 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 change where pointer variable can point to the new variable later in the program.
In C we only have pointer and value variables, whereas in C++ we have a pointer, reference and value variables. In my linked answer I tried to explain differences between pointer and reference variable.