据说*C 中的运算符意味着"指向变量的指针",并且以下代码是合法的:
#include <stdio.h>
int main(){
int a=5;
int *p=&a;
printf("%d\n", *p);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但以下代码是非法的:
#include<stdio.h>
struct pair{
int a,b;
};
int main(){
struct pair Alice, *Bob=&Alice;
Alice.a=1;
Alice.b=2;
printf("%d %d\n",*Bob.a,*Bob.b);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
那么,为什么*运算符适用于指向普通变量的指针,但是对指向结构的指针不起作用?
因为成员访问运算符.具有比间接运算符更高的优先级*.
您应该使用括号来访问没有->运算符的指向成员.
#include<stdio.h>
struct pair{
int a,b;
};
int main(){
struct pair Alice, *Bob=&Alice;
Alice.a=1;
Alice.b=2;
printf("%d %d\n",(*Bob).a,(*Bob).b);
return 0;
}
Run Code Online (Sandbox Code Playgroud)