error: invalid conversion from 'int' to 'int*'int *q = 8;
Works fine.*q = 6;
Why can't I directly assign an int to an int pointer like this: int *q = 6
; and I can assign it safely in the next line?
You can assign 0 into a pointer: ptr = 0; The null pointer is the only integer literal that may be assigned to a pointer.
The key is you cannot use a pointer until you know it is assigned to an address that you yourself have managed, either by pointing it at another variable you created or to the result of a malloc call.
And, int *p = 6; means define a variable named p with type int* and initialize it with 6 , which fails because 6 can't be used for initializing a pointer directly (i.e. the error "invalid conversion from 'int' to 'int*'"). Follow this answer to receive notifications.
The C++ language allows you to perform integer addition or subtraction operations on pointers.
Because they're different things at all. The 1st one is definition of variable with initializer expression, i.e an initialization (of the pointer itself):
int * q = 8;
~~~~~ ~ ~~~
type is int*; name of variable is q; initialized with 8
The 2nd one is assignment (of the object pointed by the pointer):
*q = 6;
~~ ~~~
dereference on q via operator*; assign the resulting lvalue pointed by q to 6
And, int *p = 6;
means define a variable named p
with type int*
and initialize it with 6
, which fails because 6
can't be used for initializing a pointer directly (i.e. the error "invalid conversion from 'int' to 'int*'").
*
symbol is reused for two different purpuses in your snippet. First time it is used as a part of type declaration int *
, declaring a pointer to int. Second time it is used to dereference a pointer *q
, invoking indirection operator.
*
can also be used to invoke multiplication operator *q = *q * *q;
;
To assign a value to an integer pointed by pointer you need to dereference it. And to assigning integral value other than 0 to a pointer itself (that is what int *q = 8;
is doing) requires reinterpret_cast
, hence you get this error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With