tags:

views:

97

answers:

5

Is it posible to declare a global array of a struct, and add elements dynamically to it?

Thanks.

A: 

No, not directly. But you may use a STL or self-made vector.

mbq
+1  A: 

See std::vector.

Any time you're tempted to use an array, you'd probably do better to use a vector, list, or one of the many other STL containers.

Cogwheel - Matthew Orlando
+4  A: 

If you want to dynamically add elements to something, you might consider using a list. You could create a global list, and dynamically add elements to it as needed. If you really need array type functionality, a vector might be more your speed. In this case, the STL is likely to provide what you need.

It's also good to note that globals aren't always a good idea. If you're using globals a lot, you may want to consider refactoring your code so they won't be necessary. Many people consider global variables to be a code smell.

Benson
A list is exactly what I need. Thanks!!
NeDark
+1 std::vector's aren't the only fruit
jk
@NeDark: Glad this is what you were looking for! @jk: Thanks!
Benson
A: 

You can use a STL container. Alternatively you can declare of your type and allocate/deallocate memory by yourself. But you should not use the 2nd way.

DaClown
+3  A: 

Avoid using non-PODs as globals. However, you can do this:

std::vector<YourStruct>& global_list()
{
    static std::vector<YourStruct> v;
    return v;
}

This at least avoids global initialization order problems by enforcing a policy where access is initialization. Otherwise you'll very easily wander into undefined behavior land.

As for what variable-sized container to use, it's hard to tell without more contextual information. Do you need to be able to quickly search for elements in the list, for example? Will you be removing elements from the middle of the list frequently? Do you need random-access, or is sequential iteration fine? Etc. etc.