简体   繁体   English

C. malloc一个结构数组,该结构数组具有一个结构指针作为成员变量

[英]C. malloc a struct array which has a struct pointer as a member variable

I have two structs: 我有两个结构:

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

struct Child {
   int id;
}

I wish to init an array of 'Parent' 我想初始化一个“父母”数组

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

this breaks when runs. 运行时会中断。

Any solution for this? 有什么解决办法吗?

I want to initialize in such way: 我想以这种方式初始化:

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

Since you mentioned you wanted C - you could use memset to initialize the memory (including the child pointer) to all zeroes. 既然您提到了您想要的C-您可以使用memset将内存(包括child指针)初始化为全零。

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

This will initialize the entire parents array to all zeroes. 这会将整个parents数组初始化为全零。 Otherwise it will be initialized to whatever happened to be in the memory when it was allocated. 否则,它将被初始化为分配时内存中的任何内容。

The proper solution in C++ will be significantly different (use new[] and constructors to initialize the structs). C ++中的正确​​解决方案将大不相同(使用new[]和构造函数来初始化结构)。

In C I use calloc() instead of malloc() . C我使用calloc() 而不是 malloc()

Because, calloc() zeroes the memory returned, malloc() doesn't. 因为calloc()将返回的内存清零,所以malloc()不会。

But if you want to zero memory after allocation, I personally prefer bzero() because it's unambiguous about it's purpose and takes one fewer argument than memset() does. 但是,如果您想在分配后将内存归零,我个人更喜欢bzero()因为它的目的是明确的,并且比memset()少了一个参数。 I would generally use memset() can fill with non-zero values for that reason. 出于这个原因,我通常会使用memset()可以填充非零值。

Chris Vig brings up a good point, but I think what you were tying to do was this 克里斯·维格(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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM