如何解决C语言中“expected ‘)’ before ‘->’ token”编译报错问题
编译错误定位与修正方案
报错根因
你遇到的第8行、第43行报错,本质是混淆了函数声明/定义的语法规则和函数调用的传参语法:C语言要求函数的声明、定义阶段,必须在形参位置写清楚「参数类型 + 形参变量名」,不能直接把调用时才用的实参表达式、成员访问、取地址符号写在形参列表里。
逐点列出所有触发编译错误的代码问题
- 第8行的函数原型语法错误:
原代码写的void printAttributes(de->d_name, &statBuff);完全不符合声明规则:既没有给两个参数指定类型,还直接引用了还没定义的de变量、写了de->d_name的成员访问表达式、加了仅在传参场景使用的取地址符&,编译器无法识别参数类型,直接抛出语法错误。 - main内自定义空结构体的冗余错误:
原代码写的struct stat{ } statBuff;会直接覆盖sys/stat.h头文件中已经定义好的、包含完整文件属性字段的struct stat类型,不仅多余,还会导致后续stat()系统调用出现类型不匹配的问题。 - 标准库函数拼写错误:
原代码里的getChar()大小写错误,标准库提供的控制台单字符读取函数是全小写的getchar()。 - 第43行的函数定义语法错误:
原代码写的void printAttributes(de->d_name, &statBuff){...}和第8行的原型错误完全一致,把函数调用的传参写法错放到了函数定义的形参位置,编译器无法识别形参的类型和名称,触发报错。
修正后的可编译代码框架
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #include <dirent.h> #include <sys/stat.h> // 规范的函数原型:明确标注每个参数的类型与形参名 void printAttributes(const char *file_name, const struct stat *stat_info); int main(){ // 直接使用头文件预置的struct stat类型,无需自定义空结构体 struct stat statBuff; int err; struct dirent *de; DIR *dr = opendir("."); if (dr == NULL) { printf("Could not open current directory\n"); return 0; } while ((de = readdir(dr)) != NULL){ err = stat(de->d_name, &statBuff); printf("%s\n", de->d_name); if(err == -1){ printf("Error in Stat\n"); printf("Press 'Enter' to continue\n"); getchar(); // 修正函数名拼写 return 1; } // 函数调用位置的传参逻辑本身没有问题,保持原写法即可 printAttributes(de->d_name, &statBuff); } closedir(dr); return 0; } // 规范的函数定义:形参位置按语法要求书写 void printAttributes(const char *file_name, const struct stat *stat_info){ // 在此处补充文件属性的打印逻辑即可 }
注意:main函数里写的
printAttributes(de->d_name, &statBuff)属于函数调用场景,这里的传参写法本身是正确的,不需要修改。所有报错都来自函数声明、函数定义阶段的形参列表书写错误。
内容的提问来源于stack exchange,提问作者Lakeguy556
相关产品推荐
相关产品推荐

