【发布时间】:2018-01-05 18:20:50
【问题描述】:
如何检查代码中定义的结构的递归子代是否为 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? -
首先,您需要使用
malloc为某处的fs分配有效指针,然后使用memset将整个事物初始化为零。