简体   繁体   English

C 链表结构中的未知类型名称

[英]Unknown type name in C linked list structure

I got a structure like this in a header file:我在 header 文件中得到了这样的结构:

typedef struct {
    LIGNE *precedent;
    PERSONNE individu;
    LIGNE *suivant;
} LIGNE;

But when I compile, I got this error:但是当我编译时,我得到了这个错误:

error: unknown type name ‘LIGNE’
  LIGNE *precedent;
  ^~~~~
error: unknown type name ‘LIGNE’
  LIGNE *suivant;

I don't understand where is the problem.我不明白问题出在哪里。

Put yourself in compilers shoes:把自己放在编译器的鞋子里:

1: typedef struct {
2:     LIGNE *precedent;
3:     PERSONNE individu;
4:     LIGNE *suivant;
5: } LIGNE;

In line 2 you say that you want a pointer to something of type LIGNE .在第 2 行中,您说您想要一个指向LIGNE类型的指针。 That's a problem for compiler since it has no idea what LIGNE is until line 5. Granted, this is compiler being a little dumb.这对编译器来说是个问题,因为直到第 5 行它才知道LIGNE是什么。当然,这是编译器有点笨。 A pointer to anything is the same size, so as far as layout of structure goes, it shouldn't matter.指向任何东西的指针大小相同,因此就结构布局而言,这无关紧要。 However, C compiler wants to know what sort of pointer this.但是,C 编译器想知道这是什么类型的指针。 As @Gerhardh suggested, you can trick it by prefixing lines 2 and 4 with struct .正如@Gerhardh 所建议的那样,您可以通过在第 2 行和第 4 行前加上struct来欺骗它。 Compiler sees this and reads it as pointer to structure , suddenly no longer caring that it knows not anything about it.编译器看到这一点并将其作为指向结构的指针读取,突然不再关心它对它一无所知。

This will work这将起作用

typedef struct {
    struct LIGNE *precedent;
    PERSONNE individu;
    struct LIGNE *suivant;
} LIGNE;

As said in the commants and in the Tomo Ceferin 's answer, your compiler has no idea of what LIGNE is until line 5.正如评论和Tomo Ceferin的回答中所说,您的编译器直到第 5 行才知道LIGNE是什么。

One solution would be to typedef your structure before its declaration:一种解决方案是在声明之前对您的结构进行 typedef:

typedef struct S_LIGNE LIGNE;

struct S_LIGNE {
    LIGNE *precedent;
    PERSONNE individu;
    LIGNE *suivant;
};

This way, your compiler knoww that LIGNE is a typedef for struct S_LIGNE .这样,您的编译器就知道LIGNEstruct S_LIGNE的 typedef。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM