How to make an array with my structure types?

In C # .NET. I can use List<myclasstype> vals = new List<myclasstype> ();what can be done equivalently in C?

I have a structure like:

typedef struct foo {
    int x;
    int y;
} Baa; 

and I want to do:

**BAA vals = ?? 
int i ;
for(i = 0; i < size; i++)
{
   vals[i].x = i;
   vals[i].y = i * 10;
}

Hope this is clear to you. Thanks in advance.

+5
source share
1 answer

This is the same as creating any other array in C, except that the type is replaced with Baa

int size = 5;
Baa baaArray[size];

int i;
for(i = 0; i < size; i++)
{
   baaArray[i].x = i;
   baaArray[i].y = i*10;
} 

You can also use pointers and malloc for this:

int size = 5;
Baa *baaPtr = malloc(sizeof(Baa) * size);

//...

Hope this helps.

+6
source

All Articles