Teererai Marange Teererai Marange - 1 month ago 6
C++ Question

c++ trying to initialize values in 2d array

I have created a 2d array called digits and would like to initialize each of the subarrays one by one to make my code clearer. I understand that the following code works:

string digits[2][5] = { { " - ","| |"," ","| |"," - " },{ " - ","| |"," ","| |"," - " } };


But am wondering why the following doesn't work:

string digits[2][5];
digits[0] = { " - ","| |"," ","| |"," - " };
digits[1] = { " - ", "| |", " ", "| |", " - " };

Answer

The 2nd one is not initialization, it's assignment (of elements of digits).

string digits[2][5];                               // initialization
digits[0] = { " - ","| |","   ","| |"," - " };     // assignment of the 1st element of digits
digits[1] = { " - ", "| |", "   ", "| |", " - " }; // assignment of the 2nd element of digits

The element of digits is an array, the raw array can't be assigned as a whole.

Objects of array type cannot be modified as a whole: even though they are lvalues (e.g. an address of array can be taken), they cannot appear on the left hand side of an assignment operator

You could do this with std::array or std::vector, which could be assigned with braced initializer.

std::array<std::array<std::string, 5>, 2> digits;
digits[0] = { " - ","| |","   ","| |"," - " };
digits[1] = { " - ", "| |", "   ", "| |", " - " };
Comments