【问题标题】:Check if recursive children of struct are NULL (C Language)检查结构的递归子代是否为 NULL(C 语言)
【发布时间】: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-&gt;child[i] == NULL 和这一行fs-&gt;child[i] = e 它在运行时返回Segmentation fault: 11。我做错了什么?

【问题讨论】:

  • 您没有为fs 分配有效的指针值。所以fs-&gt;... 是非法地址引用。
  • 你在哪里创建fs?
  • 首先,您需要使用malloc 为某处的fs 分配有效指针,然后使用memset 将整个事物初始化为零。

标签: c recursion struct


【解决方案1】:

FS *fs; 应该改为 FS *fs = (FS*) malloc (sizeof(FS));。您很可能知道如何分配内存块,但您似乎忘记了它。不过别忘了free(fs);

【讨论】:

猜你喜欢
  • 2014-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多