【问题标题】:Recursive structure definition in C, error "forward declaration"C 中的递归结构定义,错误“前向声明”
【发布时间】:2015-05-27 11:54:59
【问题描述】:

我想将我的结构声明为递归结构。所以到目前为止我所做的看起来是这样的:

 typedef struct {

 char *string;
 struct my_struct **children; //I want a list of children, therefore pointer to pointer
 int child_num;
 } my_struct;

但是当我尝试像这样初始化它时:

my_struct *alig;
alig = malloc(sizeof(my_struct)*1);
alig->child_num = 5;
alig->string = malloc(sizeof(char)*9);
strncpy(alig->string, "AAACGTCA", 8);

alig->children = malloc(sizeof(my_struct*)*alig->child_num);

int j;
for (j = 0; j < alig->child_num; j++) {
    alig->children[j] = malloc(sizeof(my_struct)*1);
    alig->children[j]->string = malloc(sizeof(char)*9); // *********error ********
}

我得到错误: "./structurs.h:27:13: 注意:'struct my_struct' 的前向声明"

以及标记行处的此错误: main.c:56:22:错误:“struct my_struct”类型的定义不完整

现在有人知道我的错误在哪里吗?

【问题讨论】:

  • (除了 typedef)你对strncpy() 的使用是错误的。 (使用 strncpy()总是错误)

标签: c recursion


【解决方案1】:

你的代码中没有struct my_struct,你的struct是匿名的typedef,你需要它是这样的

typedef struct my_struct {
     char *string;
     struct my_struct **children;
     int child_num;
} my_struct;

甚至

typedef struct my_struct my_struct;
struct my_struct {
     char *string;
     my_struct **children;
     int child_num;
};

【讨论】:

  • 我是盲人-.-!!非常感谢!
【解决方案2】:

在您的代码中

typedef struct {
 char *string;
 struct my_struct **children; 
 int child_num;
 } my_struct;

没有定义一个名为struct my_struct的struct,而是将typedefs my_struct定义为一个未命名结构的别名。所以你不能在你的代码中使用struct my_struct。要么

要么

  • 您需要将typedef 放在结构定义之前。

或

  • 您需要使用命名struct。

【讨论】:

    【解决方案3】:
     typedef struct {
    
     char *string;
     struct my_struct **children; //I want a list of children, therefore pointer to pointer
     int child_num;
     } my_struct;
    

    应该是

     typedef struct my_struct{
    
     char *string;
     struct my_struct **children; //I want a list of children, therefore pointer to pointer
     int child_num;
     } my_struct;
    

    正如 @iharob 所说,您的代码中没有结构 my_struct,编译器抱怨它您首先显示了一个结构 my_struct,然后为您的结构提供了一个 typedef

    【讨论】:

      猜你喜欢
      • 2015-05-17
      • 2010-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-02
      相关资源
      最近更新 更多