How can I malloc a set of memory and then put a set of structs into that memory?
Here is what I mean...let's say I want to put five integers into memory and then retrieve them (of course, I could use an array, linked list, etc.):
Code:
#include <stdio.h>
#include <stdlib.h>
int main (void) {
int * dataset;
int i;
dataset = malloc ( sizeof (int) * 5 );
*(dataset) = 9000;
*(dataset+1) = 10000;
*(dataset+2) = 11000;
*(dataset+3) = 12000;
*(dataset+4) = 13000;
for (i=0; i<5;i++)
printf ("position %i value %i\n",i,*(dataset+i));
}
That works fine. But now let's say instead of integers, I want to put structs in memory. And in fact I have several million of these structs, and I don't know the number ahead of time, so an array is not possible.
This won't work:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct person_struct {
char name[20];
int age;
};
int main (void) {
int * dataset;
int i;
struct person_struct this_person;
dataset = malloc ( sizeof (struct person_struct) * 5 );
strcpy(this_person.name,"Bob");
this_person.age = 20;
*(dataset) = this_person; // error: incompatible types in assignment
}
Of course, I could malloc each struct and put a pointer to it in dataset, but then I might as well use a linked list or other tree.
So how can I say "here is a struct, and here is a big pile of memory I've malloc'd. Store that struct at position 10. Now store the next one at position 11. Etc." Then once I have them, I can access them through pointer arithmetic and sort them.