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


Array initialization doesn't work

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