Reputation: 37
Lets pretend I have a struct like this..
typedef struct _my_struct {
int a;
int b;
} my_struct;
Now if I did something like this..
my_struct data[20];
Would give me an array of 20 structs which I can access by doing..
data[0].a = 5;
data[5].b = 10;
etc..
However, what if I don't know the number that I need at compile time? So then I do something like..
my_struct *data = malloc(sizeof(my_struct) * 20);
The issue is now I don't know how to reference each struct in this buffer of memory.
Upvotes: 0
Views: 106
Reputation: 36680
As pointed out in the comments, the means of referencing the data is the same. The only difference is that in the first case the memory for the struct is allocated on the stack.
my_struct data[20];
While in the second case the memory is allocated on the heap.
my_struct *data = malloc(sizeof(my_struct) * 20);
While the syntax for accessing the data is the same.
data[0].a = 5;
data[5].b = 10;
etc..
The different approaches have important implications for your program, especially when you are passing information to and from functions, and it does mean you need to remember to free the memory you've allocated.
Upvotes: 1