开发者

Why won't this array initialize?

开发者 https://www.devze.com 2023-02-26 06:14 出处:网络
This is essentially what I\'m trying to do, but not the actual source code. namespace namespace { int array [3];

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

namespace namespace { int array [3]; } name开发者_运维百科space::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?


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;


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));
}

!


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


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};
0

精彩评论

暂无评论...
验证码 换一张
取 消