Referencing struct within another in C

1

I need to have a reference of struct within the other. But in the example below as struct TAnimal does not yet exist, its reference to struct player of error. How to get around this situation?

 typedef struct jogador{
    char nome[50];
    TAnimal* animal;
 }TJogador;

typedef struct animal{
    char nome[50];  
    TJogador* jogador;
}TAnimal;
    
asked by anonymous 18.03.2017 / 13:18

1 answer

3

When there is cyclic reference you have to declare the structure before using it and then define it later. See What's the difference between statement and definition? .

#include <stdio.h>

typedef struct animal TAnimal;

 typedef struct jogador {
    char nome[50];
    TAnimal* animal;
 } TJogador;

struct animal {
    char nome[50];  
    TJogador* jogador;
};

int main(void) {
    TJogador jogador = { .nome = "abc" };
    TAnimal animal = { .nome = "hipopo", .jogador = &jogador };
    jogador.animal = &animal;
}

See running on ideone . And at Coding Ground . Also put it on GitHub for future reference .

    
18.03.2017 / 13:57