如何修复C代码中的‘error: 'a' is a pointer; did you mean to use '->'?’错误?
修复C代码中“'a' is a pointer; did you mean to use '->'?”错误
错误原因
问题出在newm函数里的*a.moo = 5;这行代码。C语言中,结构体成员访问运算符.的优先级高于指针解引用运算符*,编译器会优先处理a.moo——但a是struct cow*类型的指针,不能直接用.访问结构体成员,因此触发报错。
两种修复方案
方案1:使用->运算符(推荐)
->是C语言专门为指针访问结构体/联合体成员设计的运算符,写法简洁,直接替换原有错误代码即可:
void newm(struct cow *a){ a->moo = 5; }
方案2:添加括号调整运算优先级
通过括号让指针解引用*a先执行,将指针转换为结构体变量后,再用.访问成员:
void newm(struct cow *a){ (*a).moo = 5; }
这种写法和a->moo功能完全等价,只是可读性稍差。
修复后的完整代码
#include <stdio.h> struct cow{ int moo; }; void newm(struct cow *a){ a->moo = 5; } int main() { printf("Hello world"); struct cow a; newm(&a); printf("hallo %i", a.moo); return 0; }
内容的提问来源于stack exchange,提问作者Rajvir B
相关产品推荐
相关产品推荐

