Self-relational structures in c

I am trying to move some code that compiles like C ++ in VS2010 to c (gcc c99) and I get compilation errors. This is slightly different from other self-referencing questions because I have 2 user types, each of which contains pointers to each other. It seems that my forward declarations are not enough.

struct potato; //forward declare both types
struct tomato;

struct potato
{
    potato* pPotato; //error: unknown type name β€˜potato’
    tomato* pTomato;

};

struct tomato
{
    potato* pPotato;
    tomato* pTomato;
};

Why does this not work in gcc 99? Why is this normal, like C ++ code? How do I change this to get the same behavior as c99?

+4
source share
3 answers

Alternatively, typedefboth of them

typedef struct potato potato; //forward declare both types
typedef struct tomato tomato;

struct potato
{
    potato* pPotato;
    tomato* pTomato;

};

struct tomato
{
    potato* pPotato;
    tomato* pTomato;
};
+8
source

C, C struct / struct, .

, , p.

:

struct potato; //forward declare both types
struct tomato;

struct potato
{
    struct potato* potato;
    struct tomato* tomato;

};

struct tomato
{
    struct potato* potato;
    struct tomato* tomato;
};

struct foo typedef:

typedef struct potato potato;

struct potato inline:

typedef struct { ... } potato;

, typedef struct "longhand", struct, .

+4

struct potato
{
    struct potato* pPotato;
    struct tomato* pTomato;

};

Plain C typedef .

typedefing ( posfix, , typedef ), :

#define Struct(Nam,...) typedef struct Nam Nam; struct Nam __VA_ARGS__

Struct(tomato,);
Struct(potato,);

Struct( potato, {
    potato* pPotato; //error: unknown type name β€˜potato’
    tomato* pTomato;

});

Struct(tomato, {
    potato* pPotato;
    tomato* pTomato;
});

tomato tom;
potato pot;
+1

Source: https://habr.com/ru/post/1662699/


All Articles