Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically allocated array of structures in C

I just wanted to know if the following works. I have a struct called foo that is defined as the following:

struct foo {
    char name[255];
    int amount;
};

During runtime, I need to create an array of the above structures whose size is dependent on a value I receive from a file's input. Let's say this size is k. Will the following code appropriately allocate a dynamically-sized array of structures?

struct foo *fooarray;
fooarray = malloc(k * sizeof(struct foo));

EDIT: If I want to access members of the structures within these arrays, will I use the format fooarray[someindex].member?

like image 886
user3059347 Avatar asked Dec 12 '25 10:12

user3059347


1 Answers

That will work (and your accessing is correct). Also, you can guard against size errors by using the idiom:

fooarray = malloc(k * sizeof *fooarray);

Consider using calloc if it would be nice for your items to start out with zero amounts and blank strings, instead of garbage.

However, this is not a VLA. It's a dynamically-allocated array. A VLA would be:

struct foo fooarray[k];
like image 135
M.M Avatar answered Dec 14 '25 09:12

M.M



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!