Domanda

I have the following sample code :

person.h

typedef struct person Person;
Person* makePerson(char* n, int i);

person.c

#include "person.h"
struct person {
    char* name;
    int age;
};

Person* makePerson(char* n, int i) {
    Person person;
    person.name = n;
    person.age = i;
    return &person;
}

main.c

#include <stdio.h>
#include "person.h"
int main() {
    Person* pp = makePerson("Mark",24);
    printf("Person's name : %s\t Person's age : %d\n",pp->name, pp->age);
}

I am getting an error of "dereferencing pointer to incomplete type" when I attempt to print out the name and age members that correspond to the Person pointer, pp.

I am using gcc-std=c99 -o main main.c person.c to compile

Can anyone give me some guidance? Thanks

È stato utile?

Soluzione

This line:

printf("Person's name : %s\t Person's age : %d\n",pp->name, pp->age);

dereferences the person struct. However, your .h file includes merely a forward declaration.

Either put the print function into person.c, or move the full struct definition into person.h.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top