user569363
user569363

Reputation: 31

Why won't this array initialize?

This is essentially what I'm trying to do, but not the actual source code.

namespace namespace { int array [3]; } namespace::array={1,2,3}

my gcc asks for an expression, and I'm not sure of what to do. Must I namespace::array[1]; each individual element?

Upvotes: 0

Views: 286

Answers (4)

Dmitrii Volosnykh
Dmitrii Volosnykh

Reputation: 1185

There are several ways:

1) Explicitly set values for each element:

namespace ns {
    int array [3];
}
ns::array[0]=1;
ns::array[1]=2;
ns::array[2]=3;
\\ or if they should contain consequtive values:
\\ for (size_t i = 0; i < 3; ++i)
\\     ns::array[i] = i + 1;

2) If you want initialize static array in place of its declaration, then you could move it initializer list as follows:

namespace ns {
    int array[3] = {1, 2, 3};
}

3) Use typedef:

namespace ns {
    typedef int array_t[3];
}
ns::array_t array = {1, 2, 3};

3) Also you can make some research of std::tr1::array, which may be used as such:

std::tr1::array<int, 3> arr = {1, 2, 3};

Upvotes: 0

Richard Pennington
Richard Pennington

Reputation: 19975

Although it an odd mixture of C99 and C++, gcc allows this:

#include <string.h>
int a[3];

int main()
{
    memcpy(a, (int[3]){ 1, 2, 3}, sizeof(a));
}

!

Upvotes: 3

NPE
NPE

Reputation: 500713

How about namespace ns { int array[3] = {1, 2, 3}; }?

Upvotes: 0

Erik
Erik

Reputation: 91300

You can only use an initializer list in a definition:

int array[3] = { 1, 2, 3 };

If you use:

int array[3];

then you need to initialize the array in a function, using

array[0] = 1; 
array[1] = 2; 
array[2] = 3;

Upvotes: 6

Related Questions