C语言中传递数组内结构体指针的编译问题
编译错误解决方法
错误原因分析
- C2373错误:
remove是C标准库的内置函数(声明在<stdio.h>中,用于删除文件),你的自定义函数与它重名,且类型修饰符不一致,导致重定义冲突。 - C4133警告:编译器将你的
remove识别为标准库函数(参数要求为const char*),但你传入的是struct queue*类型,类型不匹配引发警告。
具体修复步骤
- 重命名自定义函数:将
remove改为其他名称,比如queue_remove,避开标准库函数名冲突。 - 修正返回值修饰符:函数返回的是局部变量的拷贝,
const char修饰无意义,改为char即可。 - 规范
main函数定义:C标准要求main函数返回类型必须为int,不能省略。
修改后的完整代码
typedef struct querec *queptr; struct querec { char item; queptr next; }; struct queue { queptr front, rear; }; struct queue qnum[5]; char item; char queue_remove(struct queue *q) { queptr p; char remove_result; p = q->front; remove_result = p->item; q->front = p->next; if (q->front == NULL) q->rear = NULL; return remove_result; } int main() { // ... 原有代码 item = queue_remove(&qnum[3]); return 0; // 符合C标准的返回语句 }
额外提示
如果队列可能为空,建议在queue_remove函数开头增加空队列判断,避免访问空指针导致崩溃:
char queue_remove(struct queue *q) { if (q->front == NULL) { // 可根据需求处理,比如返回标记字符或用断言终止程序 assert(q->front != NULL); } // ... 原有代码 }
内容的提问来源于stack exchange,提问作者Derek Johnson
相关产品推荐
相关产品推荐

