NeDark
NeDark

Reputation: 1294

How to make a global array with variable number of elements?

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

Thanks.

Upvotes: 3

Views: 542

Answers (5)

stinky472
stinky472

Reputation: 6797

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.

Upvotes: 3

DaClown
DaClown

Reputation: 4569

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.

Upvotes: 0

Benson
Benson

Reputation: 22847

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.

Upvotes: 4

Cogwheel
Cogwheel

Reputation: 23217

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.

Upvotes: 1

mbq
mbq

Reputation: 18628

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

Upvotes: 0

Related Questions