Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I directly assign an int to an int pointer like this: int *p = 6;?

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?

like image 897
Aquarius_Girl Avatar asked Jul 07 '17 09:07

Aquarius_Girl


People also ask

Can you assign an integer to a pointer?

You can assign 0 into a pointer: ptr = 0; The null pointer is the only integer literal that may be assigned to a pointer.

Can we directly assign value to 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.

What does this declaration mean int p 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*'"). Follow this answer to receive notifications.

Can you add an integer to a pointer C++?

The C++ language allows you to perform integer addition or subtraction operations on pointers.


2 Answers

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*'").

like image 102
songyuanyao Avatar answered Sep 23 '22 14:09

songyuanyao


* 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.

like image 44
user7860670 Avatar answered Sep 23 '22 14:09

user7860670