Reputation: 2132
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] = { " - ", "| |", " ", "| |", " - " };
Upvotes: 2
Views: 100
Reputation: 111
If you're changing this line for clarity, also consider:
string digits[2][5] = {
{" - ", "| |", " ", "| |", " - "},
{" - ", "| |", " ", "| |", " - "}
};
Note: Consider. Indentation is a powerful tool, but it can be misused.
Upvotes: 1
Reputation: 3911
initialization is far different from assignment. initialization is assigning a value to variable while declaring (invoking constructor) whereas assignment is to declare then assign (invoking assignment operator). to assign correctly you remove brackets and then you use a loop or manually eg:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s[2][3];
string Hi = "Hi there!";
s[0][0] = "Hello there!";
//....
for(int i(0); i < 2; i++)
for(int j(0); j < 3; j++)
s[i][j] = Hi;
for(int i(0); i < 2; i++)
for(int j(0); j < 3; j++)
cout << s[i][j] << endl;
return 0;
}
Upvotes: 2
Reputation: 173044
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] = { " - ", "| |", " ", "| |", " - " };
Upvotes: 2