how to make an array with my struct types?

8.9k views Asked by At

In C#.NET I can to use List<myclasstype> vals = new List<myclasstype> (); it's possible do equivalent to in C?

I have an struct like:

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

and I want do:

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

I hope this is clear for you. Thanks in advance.

1

There are 1 answers

3
Hunter McMillen On BEST ANSWER

It is the same as you would create 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 to accomplish this:

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

//...

Hope this helps.