如何檢查在我的代碼中定義的結構的遞歸子項是否爲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'將所有東西初始化爲零。 –