3

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

Thanks.

2
  • 4
    Yes, as others have said, std::vector<> is what C++ has for variable-length arrays. However, global variables are frowned upon and that's for good reason. Why do you want it to make a global? Commented Jun 30, 2010 at 5:23
  • 1
    See that "global" and "with variable contents" are totally orthogonal concepts. Commented Jun 30, 2010 at 7:09

5 Answers 5

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@NeDark: Glad this is what you were looking for! @jk: Thanks!
3

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.

Comments

1

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.

Comments

0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.