February 11th, 2013, 02:08 PM
Originally Posted by comi
does anyone knows how can i create an array of structs and how can i get every struct address?
actually i dont know the size of the array and i tried something like
but it doesnt work.
structname *example would serve to point to the dynamically created array, but it is useless until you have initialized it with memory to contain that array. Since this is C, you would use malloc thus:
example = malloc(sizeof(structname)*ARRAY_SIZE);
where ARRAY_SIZE would be a macro (AKA "a #define") representing the number of elements in the array.
You don't know what size to make the array, so malloc it first with some arbitrary size. I would use 10 just because it's a not-too-big round number, but you could even use 1. Then when you have filled that array and need to add more, use realloc()
to change the size of the array. You could add one more element with each call to realloc, but I would think that that operation would slow your program down a bit, so I would be inclined to add multiple elements each time, like say another 10. Or you could just add one at a time and see how well it works.
You should also be keeping in an integer variable a count of the number of structs you have in that array.
Merci, schadocalex! I didn't see where he said that he doesn't know ahead of time how many structs he'll have to store in the array.
Last edited by dwise1_aol : February 11th, 2013 at 02:11 PM.