当我将结构传递给函数时,出现错误:应为“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: error: incompatible type for argument 1 of ‘showBooks’
showBooks(book1);10:5: note: expected ‘struct book’ but argument is of type ‘struct book’ int showBooks(struct book x);
31:12: error: incompatible type for argument 1 of ‘showBooks’
showBooks(book2);10:5: note: expected ‘struct book’ but argument is of type ‘struct book’ int showBooks(struct book x);
哪里出错了?
最佳答案
您的两个不同的结构定义定义了两种不同的类型。尽管它们都称为 struct book
,但它们不是同一类型。
您的变量 book1
和 book2
具有局部结构类型,但该函数需要全局结构类型的结构,因此会出现错误。
您可以通过删除本地结构定义来解决问题;然后 book1
将具有全局结构等的类型。
关于c - 将结构传递给 c 中的函数时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51997050/