lab0
lab0

Reputation: 309

Error when passing struct to function in c

When I pass a struct to a function, I get the error: expected ‘struct book’ but argument is of type ‘struct book'. Why is this happening?

#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);
}

The error:

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);

where the error here?

Upvotes: 3

Views: 1404

Answers (2)

Vyshak Puthusseri
Vyshak Puthusseri

Reputation: 533

A local variable or parameter that hides a global variable of the same name. This may be confusing. The "struct book" inside the main() hides the global definition of the "struct book". The variables book1 and book2 are the type of "struct book" with local reference to the main(). The showBooks() use arguments as the book1 or book2 as formal parameters. The actual parameter uses the global definition of the "struct book" which results in incompatible type. Comment the local definition and find the difference.

Upvotes: 3

M.M
M.M

Reputation: 141574

Your two different struct definitions define two different types. Even though they are both called struct book, they are not the same type.

Your variables book1 and book2 have a type of the local struct, but the function expects a struct of the type of the global struct, hence the error.

You could fix the problem by deleting the local struct definition; then book1 will have the type of the global struct etc.

Upvotes: 5

Related Questions