Reputation: 10021
I just started learning c++ (I'm more of a java developer right now) and am having some confusion with using pointers... for example, the following code works
int main() {
int x = 5;
int * y;
y = &x; //note this line of code
*y = 10;
}
whereas this code does not work
int main() {
int x = 5;
int * y;
y = x;
*y = 10;
}
Can someone explain to me why getting the value "location" using y = &x
works but as soon as I replace it with y = x
it causes an error. If anyone knows of a good explanation on pointers please share the link :)
Thank you!
Upvotes: 0
Views: 389
Reputation: 5014
Let's see how this works with pointers.
int x = 5;
You're assigning the value 5 to x which is an int.
int *y;
You're declaring a pointer to an int.
y = &x;
Now, the address stored in y is the same as the address of x.
But, if you do this : y = x
, you're assigning an integer (5 in that case) to a variable that holds addresses of integers.
Finally, you have to remember that :
&
is the address-of operator, and can be read as "address of"*
is the indirection operator, and can be read as "value pointed to by"Upvotes: 7
Reputation: 26867
y
is a pointer to an int
. x
is an int
. Therefore whenever you set y=x
you are telling y
that whenever it gets dereferenced, it should go looking at memory location 10
(or whatever x
is at assignment time). And there probably isn't a memory allocation at 10
. Or at least not what you are expecting. If you want to get the location of x
, get a pointer to it with &x
.
int main() {
int x = 5;
int * y;
y = &x; // <-- NOTE THE "&" WHICH MEANS GET REFERENCE
*y = 10;
}
Upvotes: 0
Reputation: 611
a pointer is a variable that holds a memory location. In your instance, the variable "x" holds the value 5, where the variable y holds a location in memory. the "&" operator will enable you to use the location in memory of the "x" variable
cout >> x; //will give you an output of 5.
cout >> &x; //will give you an output of the memory location of the variable x.
y = &x;
cout >> y; //will give you an output of the memory location of the variable x.
Upvotes: 0