Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign integer literal to pointer?

Tags:

c++

c

pointers

This question might be too bad but I can take risk to post this question here to address my confusion.

Actually my question is that we can only assign address to pointer like :-

int *p,a;
p = &a; // OK
p = 1; // Error because you cannot assign integer literal to p*  

But we can assign NULL to p like :

p = NULL;

Indeed, NULL is a macro which is value is 0 and before compiling this code by compiler it get replaced with 0 by prepocessor. So after replacement its look like

 p = 0;

I know it means p is point to nothing but according to rule we can only assign address to pointer but 0 is an integer. So this isn't break the rule ?

Thanks.

like image 966
Vikas Verma Avatar asked Oct 22 '25 11:10

Vikas Verma


1 Answers

barak manos already pointed it out in his comment:

If you want to set a pointer to a literal value, you need to cast the literal value to the corresponding pointer type first.

NULL could just as well be defined as (void *) 0... which is implicitly convertible to any pointer type.

In either case, you end up with a pointer pointing to a literal address.

In no case, however, does your pointer point to memory containing a literal 4, though. This is, to my knowledge, not possible without assigning that literal value to an int first:

int i = 4;
int * p = &i;
like image 85
DevSolar Avatar answered Oct 24 '25 01:10

DevSolar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!