You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 08:20:27