Jump to content
  • Advertisement


This topic is now archived and is closed to further replies.


Array initialization doesn't work

This topic is 5748 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Let''s say I have a member array in a class and I initialize it like the following in the constructor: m_array[4] = { 0, 1, 2, 3 }; This gives me an error. What is the proper syntax for this? Or is this simply not possible? It compiles when I add the type in front of it but that''s not what I want because the array that is created is scoped only in the constructor and doesn''t exist after the constructor returns. How do you do this seemingly simple thing!?

Share this post

Link to post
Share on other sites
You can only initialize arrays. Understand the differences between initialization and definition/assignment:

int a; // declaration/definition
int b = 1; // initialization
extern int c; // declaration
a = 2; // assignment
int c; // definition
c = 3; // asignment

Arrays are not first-class types in C and C++, and as such can not be assigned (which is what you are attempting). One workaround is to initialize a temporary array and copy it into the one you''re attempting to assing:

int atmp[] = { 0, 1, 2, 3 };
memcpy( m_array, atmp, sizeof(atmp) );

Make sure you have allocated enough memory for m_array before you do this!

Share this post

Link to post
Share on other sites

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!