【发布时间】:2018-08-24 03:30:39
【问题描述】:
当我将结构传递给函数时,我收到错误:预期为“struct book”,但参数的类型为“struct book”。为什么会这样?
#include <stdio.h>
#include <string.h>
struct book
{
int id;
char title[50];
};
int showBooks(struct book x);
int main()
{
struct book
{
int id;
char title[50];
};
struct book book1,book2;
book1.id = 2;
book2.id = 3;
strcpy(book1.title, "c programming");
strcpy(book2.title, "libc refrence");
printf("Book\t\tID\n");
showBooks(book1);
showBooks(book2);
}
int showBooks(struct book x)
{
printf("%s\t%d\n", x.title, x.id);
}
错误:
30:12:错误:“showBooks”的参数 1 的类型不兼容
showBooks(book1);10:5:注意:预期为“struct book”,但参数的类型为“struct” book' int showBooks(struct book x);
31:12:错误:“showBooks”的参数 1 的类型不兼容
showBooks(book2);10:5:注意:预期为“struct book”,但参数的类型为“struct” book' int showBooks(struct book x);
哪里出错了?
【问题讨论】:
-
你用的是什么编译器?
-
gcc 版本 6.3.0
-
为什么书有两种定义?删除main里面的那个。 ideone.com/RIgIYH
-
与 book 的重新定义无关,showBooks() 函数应该返回 void。
-
大声笑,我喜欢这样的错误消息,(不是真的)。编译器应该更清楚地表明名称可能相同,但类型记录不同。用户看到这样的错误,认为编译器的龙舌兰酒太多了:(
标签: c gcc struct parameter-passing