Assign integer literal to pointer?

2020-03-30 01:46发布

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.

标签: c++ c pointers
5条回答
一夜七次
2楼-- · 2020-03-30 01:52

you can directly set the address of a pointer in c:

char * p  = reinterpret_cast<char *>( 0x0000ffff ) ;

Note that is not generally considered safe use of pointers for obvious reasons (can point anywhere in memory).

for more info see here and related question here

查看更多
走好不送
3楼-- · 2020-03-30 01:55

No it does not break the rule. The integer constant 0 (and generally any constant expression evaluating to 0) is treated specially and it is allowed to assign such value to a pointer. It does not mean that you can assign any integer - just zero.

The current version of C++ introduces the new nullptr keyword which should be used instead.

查看更多
祖国的老花朵
4楼-- · 2020-03-30 02:00

The reason for this is different in C from C++ IIRC. In C++ 0 is special literal that, by definition, can be interpreted as a null pointer of any pointer type; so in this case there is no cast from integer to pointer. To test this you can try doing this:

int i = 0;
int* p = i;

Which you will discover gives an error (See here for IDEOne example)

查看更多
兄弟一词,经得起流年.
5楼-- · 2020-03-30 02:09

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;
查看更多
6楼-- · 2020-03-30 02:11

In fact literal 0 or any constant value that is zero is an exception. It could assign to a pointer and it means a NULL or nullptr. In reverse, any null pointer evaluates to 0.

Null does not point to any memory address location, its compiler's responsibility to handle it. It is null and null is nowhere in the memory. It points to nothing.

查看更多
登录 后发表回答