c - C中的递归结构定义,错误 "forward declaration"

标签 c recursion

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

 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”的定义不完整

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

最佳答案

你的代码中没有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;
};

关于c - C中的递归结构定义,错误 "forward declaration",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30481702/

相关文章:

java - 如果我将递归调用除以另一个,是否会出现无限循环?

c - 如何将 C 中的 unix 时间戳作为 int 获取?

c - 如何合并共享库?

c - 在 C 中声明字符串与整数的二维数组?

javascript递归函数陷入无限循环

javascript - 如何使用 React 组件处理递归数组映射?

recursion - 递归组件在 Om 中工作时遇到问题?

javascript - 迭代昂贵的异步函数 - 内存限制、递归?

c - printf 指针参数类型警告?

c - 声明大数组时出现堆栈溢出异常