February 11th, 2013, 09:31 AM
Struct array in c
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.
February 11th, 2013, 11:28 AM
Did you try
> and how can i get every struct address?
// an array of 10 structname's
That would be &example[index] for all the valid subscripts of the array.
February 11th, 2013, 11:50 AM
So structname example isn't appropriated!
structname *example; may work, but it depends on the way you use it! If you don't know the size, you have to allocate it with malloc(). After that, you use it like salem showed you : &example[index].
February 11th, 2013, 02:08 PM
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:
Originally Posted by comi
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.
February 11th, 2013, 03:28 PM
Sorry, i understood it like that.
comi -> If you use realloc(), be sure to know how to use it! If realloc() fail (for any reason) and you don't operate (is the good verb? lol) it, you can say hello to difficulties, which are different from malloc().