如何检查在我的代码中定义的结构的递归子项是否为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
。我究竟做错了什么?
您没有为'fs'分配有效的指针值。所以'fs - > ...'是非法地址引用。 – lurker
你在哪里创建'fs'? –
首先,你需要在'malloc'的某处指定'fs'的有效指针,然后用'memset'将所有东西初始化为零。 –