Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A Struct with an Array of Structs with Arrays inside Them (and an Array) inside It: How would I malloc this?

I currently have no code, because I don't know how to do this at all. Could I just, by myself, calculate how many bytes is needed for each lower-level struct and malloc it to it? That's really terrible coding, isn't it. Here's the two structs I'm trying to mash together:

struct property {
    int d;
    char name [111]; // I just malloc this like I would a normal array, right?
    char descr [1025]; // Ditto.
}

struct category {
    int d [413]; // The d's of all the child structs sorted highest to lowest.
    char name [111];
    struct property property [413]; // This. How do I allocate this?
}</code>

Do I have to do struct property* property = (struct property*) malloc(sizeof(struct property) * 413);? Will the malloc of the array within remain intact? How do mallocs in structs behave in general?

like image 468
mszegedy Avatar asked Dec 07 '25 07:12

mszegedy


1 Answers

You don't have a pointer member inside your structure property so you don't need to malloc any of your structure members.
When you malloc for the structure it will give you enough memory to hold all the structure members including arrays, exceptions are pointer structure members(You don't have any).

like image 170
Alok Save Avatar answered Dec 08 '25 20:12

Alok Save



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!