Click to See Complete Forum and Search --> : resizing an array
trasher
May 8th, 2003, 08:11 AM
I suppose I have an array
mystruct* tab[..]
but how can I dynamicly add elements into it ?
I want to have a function like
addElement(myStruct *element)
{
then add *element to my array
}
I just want a hint about how I could do this
thanks
Paul McKenzie
May 8th, 2003, 08:31 AM
Originally posted by trasher
I suppose I have an array
mystruct* tab[..]
but how can I dynamicly add elements into it ?
If this is C++ and not 'C', use std::vector instead an array. There is no such thing as a dynamic array, since arrays in C++ are always fixed. So you either must use pointers with new and delete, or preferably, just create a vector of your items.
I want to have a function like
addElement(myStruct *element)
{
then add *element to my array
}
I just want a hint about how I could do this
thanks
Using vector:
#include <vector>
typedef std::vector<myStruct> MyStructArray;
MyStructArray MArray;;
void addElement(myStruct& m)
{
MArray.push_back( m );
}
You can now use MArray just like an array, including using operator [] to access and set elements.
Regards,
Paul McKenzie
PaulWendt
May 8th, 2003, 08:32 AM
You can't add elements to a statically-bound array. You'd either
have to create your own array with malloc() or new[]. Hopefully,
you're using C++; if so, you can use std::vector instead of using
a statically-bound array:
std::vector<mystruct*> v;
v.push_back(pStruct);
--Paul
Edit: I'm sorry, Paul McKenzie; I guess we posted at very similar
times :)
trasher
May 8th, 2003, 08:34 AM
thanks!
I will look for std::vector...
When I was doing C, it was so painfull to use malloc and realloc
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.