3

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?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
user3059347
  • 529
  • 1
  • 9
  • 15
  • 3
    Note that dynamically allocated arrays are very different from variable-length arrays or VLAs. You should learn that these are not VLAs so that you won't confuse other people, or be confused by other people. – Jonathan Leffler Jul 02 '14 at 02:54
  • Okay thanks for clearing that up. The difference in the terminology wasn't apparent to me before but now it is. – user3059347 Jul 02 '14 at 17:32

3 Answers3

4

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];
M.M
  • 138,810
  • 21
  • 208
  • 365
1

Yes it will.
On failure it will return 0.
And you have to free the memory returned by malloc when you are done with it

You can access the first member:

fooarray[0].name
fooarray[0].amount

The second as:

fooarray[1].name
fooarray[1].amount

etc..

odedsh
  • 2,594
  • 17
  • 17
-1

One more different notation can be used in this approach:

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

int main (void)
{
 struct foo *fooarray;
 struct foo *fooptr[5];

 unsigned int i = 0;

 for (i = 0;  i < 5; i++)
  fooptr[i] = malloc(1* sizeof(struct foo));

 fooptr[2]->name[3] = 'A';
 printf ("\nfooptr[2]->name[3]=%c\n",fooptr[2]->name[3]);
}
Ruslan Gerasimov
  • 1,752
  • 1
  • 13
  • 20