我有两个结构:
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.
}
答案 0 :(得分:1)
Don't use malloc
in C++; use new
instead
Don't cast malloc
(or other void *
values) in C
Don't use int
for size values in C; use size_t
, instead.
不要在C中使用NULL
;它不存在。请改用{{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);
}