Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialization array of two dimensional arrays

Tags:

c++

arrays

c++11

How to initialize array of two dimensional arrays in C++ (defined like in code below)?

#include <iostream>
#include <array>

typedef int arr3by6Int[3][6];
typedef arr3by6Int arr3xarr3by6Int[3];

void print3by6(arr3by6Int arr)
{
    for(int i = 0; i < 3; i++)
    {
        for(int j = 0; j < 6; j++)
        {
            std::cout << arr[i][j] << " ";
        }
        std::cout << std::endl;
    }
}
int main(int argc, char const *argv[])
{

    arr3by6Int a = {
        {1,2,3,4,5,6},
        {0,0,0,0,0,0},
        {2,2,2,2,2,2}
    };

    arr3by6Int b = {
        {2,2,3,4,5,6},
        {0,0,0,0,0,0},
        {2,2,2,2,2,2}
    };

    arr3by6Int c = {
        {3,2,3,4,5,6},
        {0,0,0,0,0,0},
        {2,2,2,2,2,2}
    };

    arr3xarr3by6Int d = { a, b, c };

    for(int i = 0; i < 3; i++)
    {
        print3by6(d[i]);
    }
    return 0;
}

I get these errors:

$ g++ -std=c++11 arrays.cpp -o arrays
arrays.cpp: In function ‘int main(int, const char**)’:
arrays.cpp:39:32: error: array must be initialized with a brace-enclosed initializer
arrays.cpp:39:32: error: array must be initialized with a brace-enclosed initializer
arrays.cpp:39:32: error: array must be initialized with a brace-enclosed initializer

like image 946
user2818508 Avatar asked Sep 26 '13 08:09

user2818508


1 Answers

You have #include <array> in your code, so you should use it. Change your types to use std::array<>:

typedef std::array<std::array<int, 6>, 3> arr3by6Int;
typedef std::array<arr3by6Int, 3> arr3xarr3by6Int;

Then, update your initialization lists to match:

    arr3by6Int a = {
        std::array<int, 6>{1,2,3,4,5,6},
        std::array<int, 6>{0,0,0,0,0,0},
        std::array<int, 6>{2,2,2,2,2,2}
    };

    arr3by6Int b = {
        std::array<int, 6>{2,2,3,4,5,6},
        std::array<int, 6>{0,0,0,0,0,0},
        std::array<int, 6>{2,2,2,2,2,2}
    };

    arr3by6Int c = {
        std::array<int, 6>{3,2,3,4,5,6},
        std::array<int, 6>{0,0,0,0,0,0},
        std::array<int, 6>{2,2,2,2,2,2}
    };

In most cases, an object of "C style" array type will degrade to the pointer to the array's first element when used in an expression. Your way of initializing d is attempting to initialize the 3 matrices with pointer values, which won't work.

A std::array is a class, so it won't degrade in that way.

like image 102
jxh Avatar answered Oct 04 '22 05:10

jxh