lab*_*ab0 3 c gcc struct parameter-passing
当我将结构传递给函数时,我得到错误:期望'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);
}
Run Code Online (Sandbox Code Playgroud)
错误:
30:12:错误:"showBooks"
showBooks(book1)的参数1的不兼容类型;10:5:注意:预期的'struct book'但是参数类型为'struct book'int showBooks(struct book x);
31:12:错误:"showBooks"
showBooks(book2)的参数1的不兼容类型;10:5:注意:预期的'struct book'但是参数类型为'struct book'int showBooks(struct book x);
这里的错误在哪里?
两个不同的结构定义定义了两种不同的类型.即使它们都被调用struct book,它们也不是同一类型.
你的变量book1并且book2有一个本地结构的类型,但是函数需要一个全局结构类型的结构,因此错误.
您可以通过删除本地结构定义来解决问题; 那么book1将具有全局结构的类型等.