How can I initialize 2d array with a list of 1d arrays?
void main()
{
int a[] = { 1,2,3 };
int b[] = { 4,5,6 };
int array[][3] = { a,b };
}
The way you presented - not at all... You can have:
int array[][3] = { { 1, 2, 3 }, { 4, 5, 6 } };
If you still need a and b, you could then have these as pointers:
int* a = array[0];
int* b = array[1];
or a bit closer to your original try: References to array:
int(&a)[3] = array[0];
int(&b)[3] = array[1];
This way, you could still e. g. apply sizeof
to a
and b
...
Or the other way round: create an array of pointers
int a[] = { 1,2,3 };
int b[] = { 4,5,6 };
int* array[] = { a, b };
All these solutions presented so far have in common that both a and array[0] access exactly the same data. If you actually want to have two independent copies instead, then there's no way around copying the data from one into the other, e. g. via std::copy
.
If you switch from raw array to std::array
, though, you can have this kind of initialisation (with copies) directly:
std::array a;
std::array b;
std::array 2> array = { a, b };