C. malloc一个struct数组,它有一个struct指针作为成员变量

时间:2017-02-03 03:23:38

标签: c pointers struct

我有两个结构:

struct Parent {
   struct *Child child; // Pointer to a child
}

struct Child {
   int id;
}

我希望初始化一组父母'

int size = 2;
struct Parent *parents = (struct Parent*) malloc(sizeof(struct Parent) * size);

运行时会中断。

对此有何解决方案?

我想以这种方式初始化:

struct Parent {
    struct *Child child = nullptr; // Points to null upon initialization.
}

4 个答案:

答案 0 :(得分:1)

答案 1 :(得分:0)

由于您提到过您想要C - 您可以使用memset将内存(包括child指针)初始化为全零。

size_t size = 2 * sizeof(struct Parent);
struct Parent* parents = (struct Parent*)malloc(size);
memset(parents, 0, size);

这会将整个parents数组初始化为全零。否则,它将被初始化为分配时在内存中发生的任何事情。

C ++中的正确​​解决方案将有很大不同(使用new[]和构造函数来初始化结构)。

答案 2 :(得分:0)

C中,我使用calloc() 代替 malloc()

因为,calloc()将返回的内存归零,malloc()没有。

但是如果你想在分配后将内存归零,我个人更喜欢bzero(),因为它的目的明确无误,并且比memset()少一个参数。我通常会使用memset()填充非零值。

答案 3 :(得分:0)

Chris Vig提出了一个很好的观点,但我认为你要做的就是这个

#include <iostream>
struct Child {
   int id;
};
struct Parent {
   struct Child* c ; // Pointer to a child
};
int main() {
    int size = 2;
    struct Parent *parents = (struct Parent*) malloc(sizeof(struct Parent) * size);
}