将整数文字分配给指针? [英] Assign integer literal to pointer?

查看:76
本文介绍了将整数文字分配给指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题可能太糟糕了,但是我冒着风险在此处发布这个问题来解决我的困惑.

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;

这篇关于将整数文字分配给指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆