如何检查代码中定义的结构的递归子级是否为NULL(或为空,不使用)? (我想知道它们是否为NULL,以便可以用数据填充它们)。

#include <stdio.h>
#include <stdlib.h>

#define HEIGHT 256
#define LENGTH 256

typedef struct FS FS;
typedef struct Elem Elem;

struct Elem {
  char name[256];
  char content[256];
  Elem *child[1024];
};

struct FS {
  Elem *child[1024];
};

void create(FS *fs, char path[HEIGHT][LENGTH]){

    while(i<1024){

        if(fs->child[i] == NULL){    //check if child[i] is NULL, if so I can fill it with data

            Elem *e;
            e = malloc(sizeof (Elem));
            fs->child[i] = e;
            strcpy(e->name, path[0]);
            i = 1024;
        }
        i++;
    }
}

int main(void) {

    FS *fs;
    char path[HEIGHT][LENGTH];

    create(fs, path);

    return 0;
}


在运行时,此行fs->child[i] == NULL和此行fs->child[i] = e返回Segmentation fault: 11。我究竟做错了什么?

最佳答案

FS *fs;应该改为FS *fs = (FS*) malloc (sizeof(FS));。您很可能知道如何分配内存块,但您似乎忘记了它。但是,不要忘记使其成为free(fs);

关于c - 检查struct的递归子代是否为NULL(C语言),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45394518/

10-11 23:23
查看更多