将整数文字分配给指针?
这个问题可能太糟糕了,但是我冒着风险在此处发布这个问题来解决我的困惑.
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*
但是我们可以为p赋NULL:
But we can assign NULL to p like :
p = NULL;
实际上,NULL是一个值为0的宏,在由编译器编译此代码之前,它会由前置处理程序替换为0.因此,更换后的样子
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;
我知道这意味着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 ?
谢谢.
barak manos已经在他的评论中指出了这一点:
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
也可以定义为(void *) 0
...,它可以隐式转换为任何指针类型.
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.
但是,在任何情况下,您的指针都不会指向包含文字4
的内存 .据我所知,如果不先将字面值分配给int
,则不可能:
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;