Reference struct inside another in C

Asked

Viewed 1,133 times

2

I need there to be a reference to struct inside the other. But in the example below as the struct TAnimal does not yet exist, her reference in struct error player. How to get around this situation?

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

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

1 answer

4


When there is cyclic reference you have to declare the structure before using it and then define it later. See What is the difference between declaration 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;
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Perfect, worked!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.