2017-07-29 123 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