简体   繁体   中英

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.

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. 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).

In C I use calloc() instead of malloc() .

Because, calloc() zeroes the memory returned, malloc() doesn't.

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. I would generally use memset() can fill with non-zero values for that reason.

Chris Vig brings up a good point, but I think what you were tying to do was this

#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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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