c - 将结构传递给 c 中的函数时出错

标签 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);
}

错误:

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,但它们不是同一类型。

您的变量 book1book2 具有局部结构类型,但该函数需要全局结构类型的结构,因此会出现错误。

您可以通过删除本地结构定义来解决问题;然后 book1 将具有全局结构等的类型。

关于c - 将结构传递给 c 中的函数时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51997050/

相关文章:

objective-c - objective-c 中的#define是什么意思?

c - 无法理解 Atoi 函数 - *string - '0'

c++ - 使用 C++11 中的 unordered_map 需要哪个 gcc 版本?

struct - Racket 结构错误 : given value instantiates a different structure type with the same name

c - 访问结构数组元素

c - 我的文件指针设置错了吗?

c - 使用ascii代码, 'a' , 'b' , 'c' -> 八进制,十进制,十六进制数

c++ - gcc 中的 Borland 风格 __closure

c++ - GCC 中不可避免的可变参数模板(与 CUDA 一起使用)?

c++ - const char * 在 while 循环的下一次迭代中被覆盖