# Thread: Structure question

1. ## Structure question

Hi,

I'm just thinking about the best idea for this scenario.

I want a global structure to hold information, however when imputing this information, I want to use a parse function that will parse a text file and copy the contents into an array of structs...

This is the question...how can I allocate memory, after its already been declared. Obviously if i have x number I want x number of array of structs.

I will then use the struct in multiple functions after.

Thanks

2. Originally Posted by pc_doctor
This is the question...how can I allocate memory, after its already been declared. Obviously if i have x number I want x number of array of structs.
You can't - but you don't have to. Instead, make your global member a pointer to an array, and allocate when the program initialises. Obviously, you'll need some other way to determine the number of elements in an array (an int n_structs parameter or a zeroed-out entry or something).

e.g.:

Code:
```int n_infos;
struct info (*global_info)[];

/* initialise */
n_infos = 5;
global_info = calloc(n_infos, sizeof((*global_info)[0]));
/* error if global_info is NULL here! */```
Edit: Although this means you'd access individual elements with (*global_info)[x] - you could probably make your life easer by just declaring it a "struct info *global_info" and access it with global_info[x] instead...

3. Well if you have
Code:
`typedef struct { members; } fooType;`
You can maintain a dynamic array of them by starting with
Code:
`fooType *myArray = malloc( howManyYouWant * sizeof(*myArray) );`
But for simplicity, you might want to use limited data sets and constant sized arrays for initial testing.
Code:
`fooType myArray[SOMESIZE];`
Turning working array code into working malloc code is very easy.
Debugging errant malloc code can make you crazy

Popular pages Recent additions