David542
David542

Reputation: 110392

Ways to create a recursive data structure in C

Let's say I have some hashmap that can refer to itself, something like:

typedef struct Person {
    char* name;
    Person* mother;
    Person* father;
} Person;
Person *Bob = malloc(sizeof(Person));
bob->name = "Bob";
bob->mother = Kathy;
bob->father = Bill;

What are the suggested ways to get around the error: unknown type name ‘Person’ error?

Upvotes: 2

Views: 974

Answers (3)

Vlad from Moscow
Vlad from Moscow

Reputation: 311078

The problem is that the name Person used within the structure definition as a type specifier for data members mother and father

typedef struct Person {
    char* name;
    Person* mother;
    Person* father;
} Person;

is not yet declared.

Either use a typedef before the structure definition like

typedef struct Person Person;

struct Person{
    char* name;
    Person* mother;
    Person* father;
};

Or use the declared structure tag in the structure definition like

typedef struct Person {
    char* name;
    struct Person* mother;
    struct Person* father;
} Person;

Upvotes: 2

David542
David542

Reputation: 110392

While the typedef is not defined, the struct tag is so you can prepend that to the elements of the struct. For example:

typedef struct Person {
    char* name;
    struct Person* mother;
    struct Person* father;
} Person;
#include <stdlib.h>

int main(void) {

    // parents (ignore their parents)
    Person *Kathy = malloc(sizeof(Person));
    Kathy->name = "Kathy";
    Person *Bill = malloc(sizeof(Person));
    Bill->name = "Bill";

    // person
    Person *Bob = malloc(sizeof(Person));
    Bob->name = "Bob";
    Bob->mother = Kathy;
    Bob->father = Bill;

    printf("Name: %s | Mom: %s, Dad: %s\n", Bob->name, Bob->mother->name, Bob->father->name
    free(Bob); free(Kathy); free(Bill);

}

Name: Bob | Mom: Kathy, Dad: Bill

Upvotes: 1

entangled_photon
entangled_photon

Reputation: 457

Person is not defined yet, since the typedef only takes effect after the semicolon concluding it. To refer to the struct from within itself, use struct Person. The following code compiles with no errors on GCC 10.2.0.

typedef struct Person {
    char* name;
    struct Person* mother;
    struct Person* father;
} Person;

int main() {
    Person Kathy = { "Kathy", NULL, NULL };
    Person Bill = { "Bill", NULL, NULL };
    Person Bob = { "Bob", &Kathy, &Bill };
    return 0;
}

Upvotes: 2

Related Questions