C编程 - >链接列表和结构

时间:2015-10-15 07:58:39

标签: c linux pointers

所以我将以下内容放在.h文件中

typedef struct Supply {
      char* name;
      struct Supply* nextSupply;
      int quantity;
 } Supply;

以下

typedef struct Location {
      Supply* firstSupply;
 } Location;

我想在包含h文件的c文件中使用此片段

void snippet(Location* location, Supply* incoming) {
    Supply* first = location->firstSupply;
    Supply* check = first->nextSupply;
    if(!strcmp(first->name,incoming->name) {
          *some stuff*
    }
    *while loop checking entire linked list*
}

为什么gcc -Wall -pedantic告诉我我从无效指针类型中分配。我理解在供应的定义中我必须将nextSupply称为struct Supply *但我认为在定义完成之后然后是Supply * == struct Supply *

1 个答案:

答案 0 :(得分:0)

  

我认为这与您的问题有关。非常复杂的答案应该   修复这笔交易。

     

How to define a typedef struct containing pointers to itself?

从我的观点来看,它是结构防御范围问题。这意味着,在声明该类型的变量之前,struct定义必须在范围内。

因此,解决方法是一个前向声明,它是你的结构的声明,稍后你将在代码中定义:

typedef struct Supply Supply ;

typedef struct Supply {
      char* name;
      struct Supply* nextSupply;
      int quantity;
 } Supply;
相关问题