简体   繁体   中英

reassign pointer gives error

I am new to C++ , therefore please forgive me if my question seems basic, I am not able to reassign a pointer when I use the star, here is my code:

int val = 8;
int number = 23;
int *pointer = &val;
*pointer = &number;    //<-- error

this gives an error: assign to int from incompatible type int. here is what I tried:

pointer = &number;  // this works

therefore my question is, why is this wrong: *pointer = &number

In your code,

 *pointer = &number;    //<-- error

by saying *pointer , you're dereferencing the pointer, which is of type int , then you try to assign a pointer type value to it, which is not correct.

What you want to do, is to assign the address of a variable and to hold that, you want the pointer variable itself to be on the LHS of the assignment. So,

 pointer = &number;

is the correct way to go.

The reason this results in an error is because you misunderstood the type of each variable.

int val = 8; // type of `val` is int
int number = 23; // type of `number` is an int
int *pointer = &val; // type of `pointer` is an int *
*pointer = &number;    // type of `pointer` is int *, so type of `*pointer` is int

It doesn't work because *pointer dereferences the pointer, so you're assigning an address to a pointer, which is not what you want.

When you say

int *pointer

the * indicates that you are creating a pointer, you can think of the * as part of the data type. ie it's a pointer to an integer type. To reference the pointer itself (the type that stores an address in memory), you simply use the name of the pointer, just like a regular variable.

When you add the * infront, you are dereferencing the pointer. Meaning, you are accessing whatever is stored at the memory address that the pointer is pointing to, in this case an int.

Basically, pointer gives you an address in memory, *pointer gives you the int stored at that address.

int *pointer = &val;

Breaking this up actually means

int* pointer;
pointer = &val;

When you derefrence an integer pointer it becomes just an integer.When you add & to a non-pointer it becomes a pointer.So doing is bad,because *ptr is not a pointer and &i is a pointer

int n = 0;
int *ptr = &n //good,because they are both pointers
int i = 0;
*ptr = &i //bad because only one is a pointer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM