取消引用和组件选择之间的区别
Difference between dereferencing and component selection
在我下面的示例代码中:
#include <stdlib.h>
#include<stdio.h>
int main()
{
typedef struct {float x; float y;}C;
C z;
z.x=4;
z.y=6;
C *zpt=&z;
*zpt.x;
printf("%f",(*zpt).x);
}
我知道 (*zpt).x
或 zpt->x
用于取消引用指针。但是当我使用 *zpt.x
时出现错误,错误 - "request for member 'x' in something not a structure or union"。有人可以解释一下 *zpt.x
的作用吗?这是一个有效的语法吗?如果是,应该在哪里以及如何使用它?
这出错了*zpt.x;
因为它被解释为
*(zpt.x)
没有任何意义。首先没有 zpt.x,其次即使那是一个浮点数,你也不能在 float
上使用 *
这就是存在 -> 运算符的原因:zpt->x
与 (*zpt).x
相同,但更易于阅读和键入
你得到的错误是这样的:
error: request for member ‘x’ in something not a structure or union
正如编译器告诉您的那样,zpt
既不是结构也不是联合。问题是点运算符 (.
) 的优先级高于星号 (*
) 之一,因此首先启用点,结果你得到错误,因为编译器读作:*(zpt.x)
.
Precedence 1: . Structure and union member access
Precedence 2: * Indirection (dereference)
加上括号可以清楚地表明您希望运算符如何工作,所以
(*zpt).x
可以正常工作,但您会收到如下警告:
warning: statement with no effect [-Wunused-value]
因为你什么都不做,但我知道这只是测试代码。
我建议阅读相关问题:
Why does the arrow (->) operator in C exist?
在我下面的示例代码中:
#include <stdlib.h>
#include<stdio.h>
int main()
{
typedef struct {float x; float y;}C;
C z;
z.x=4;
z.y=6;
C *zpt=&z;
*zpt.x;
printf("%f",(*zpt).x);
}
我知道 (*zpt).x
或 zpt->x
用于取消引用指针。但是当我使用 *zpt.x
时出现错误,错误 - "request for member 'x' in something not a structure or union"。有人可以解释一下 *zpt.x
的作用吗?这是一个有效的语法吗?如果是,应该在哪里以及如何使用它?
这出错了*zpt.x;
因为它被解释为
*(zpt.x)
没有任何意义。首先没有 zpt.x,其次即使那是一个浮点数,你也不能在 float
上使用 *这就是存在 -> 运算符的原因:zpt->x
与 (*zpt).x
相同,但更易于阅读和键入
你得到的错误是这样的:
error: request for member ‘x’ in something not a structure or union
正如编译器告诉您的那样,zpt
既不是结构也不是联合。问题是点运算符 (.
) 的优先级高于星号 (*
) 之一,因此首先启用点,结果你得到错误,因为编译器读作:*(zpt.x)
.
Precedence 1: . Structure and union member access
Precedence 2: * Indirection (dereference)
加上括号可以清楚地表明您希望运算符如何工作,所以
(*zpt).x
可以正常工作,但您会收到如下警告:
warning: statement with no effect [-Wunused-value]
因为你什么都不做,但我知道这只是测试代码。
我建议阅读相关问题:
Why does the arrow (->) operator in C exist?