简体   繁体   English

将指针类型转换为&(int *)和(int *)&并将指针分配给某个指针变量时有什么区别?

[英]what is the difference while typecasting a pointer as &(int*) and (int*)& while assigning it to some pointer variable?

If we have a void pointer and we try to assign it the address of some pointer variable (for instance, a pointer to int ), then what is the difference between the statements 1 and 2. 如果我们有一个void指针,并尝试为其分配某些指针变量的地址(例如,指向int的指针),那么语句1和2之间的区别是什么?

For statement 2 , I am getting lvalue error , but I am not getting the reason behind this - ptr is lvalue only so why does it show an error? 对于语句2,我正在lvalue error ,但我没有得到这背后的原因- ptrlvalue仅为何还显示一个错误?

int a;
int *ptr =&a ;
1. void *p =(int*)&ptr;
2. void *p=&(int*)ptr;

According to section 6.5.4 of the C99 specification, line 4, footnote 89, available online here : 根据C99规范第6.5.4节第4行,脚注89,可在此处在线获取:

A cast does not yield an lvalue 强制转换不会产生左值

When we look at your code: 当我们查看您的代码时:

int a;
int *ptr =&a ;
1. void *p =(int*)&ptr;
2. void *p=&(int*)ptr;

In case of 1: A void pointer is assigned what has been typecast to int* . 在1的情况下, void指针分配已类型转换为int*指针。 This is valid. 这是有效的。 In fact the following statements also are valid: 实际上,以下语句也有效:

3. void *p = (int*)123;
4. void *p = (int*)a;
5. void *p = (int*)ptr;

But in case of 2: (int*)ptr has become an rvalue and then you are using & on that rvalue. 但是在2的情况下, (int*)ptr变成了一个右值,然后您在该右值上使用& It fails stating: lvalue required as unary '&' operand 它未能说明: lvalue required as unary '&' operand

For 2., it is not the assignment to void* that is causing the problem but the operator & on an rvalue. 对于2.,导致问题的原因不是void*的赋值,而是右值的运算符&

In your example the second one void *p=&(int*)ptr; 在您的示例中,第二个void *p=&(int*)ptr; has incorrect syntax as & requires an lvalue. 语法不正确,因为&需要一个左值。

int *n;
void *p = &n;
void *q = &(void *)n;  //incorrect syntax will not compile at all
void *w = &(int *)n;   //incorrect syntax will not compile at all

So the difference is: &(some_type *)n will not compile at all, and does not have any sense. 所以区别是: &(some_type *)n根本不会编译,也没有任何意义。
Sample code . 示例代码

&(int*)ptr is just not valid in C. &(int*)ptr在C语言中无效。

Why? 为什么? Because p and (type *)p are completely different. 因为p和(类型*)p完全不同。 p is object which reference can be obtained (type *)p is only the value without the object behind it and consequently it does not have the address. p是可以获取引用的对象(类型*)p是仅值,后面没有对象,因此它没有地址。

It is the same behaviour while casting with int : 用int强制转换时的行为相同:

int a;
int *ptr = &(int)a;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM