2017-07-29 70 views
0

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

#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。我究竟做错了什么?

+2

您没有为'fs'分配有效的指针值。所以'fs - > ...'是非法地址引用。 – lurker

+0

你在哪里创建'fs'? –

+0

首先,你需要在'malloc'的某处指定'fs'的有效指针,然后用'memset'将所有东西初始化为零。 –

回答

1

FS *fs;应改为FS *fs = (FS*) malloc (sizeof(FS));。很可能你知道如何分配一个内存块,但你似乎忘了它。但是,不要忘记制作它free(fs);

+0

[不要施放'malloc'](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – lurker

+0

@lurker所以你建议做类似而不是'FS * fs = malloc(sizeof(FS));'? –

+0

是的。请参阅我提供的链接。 – lurker