The simple answer is a shrug and "that's the way it is".
char
arrays are rather primitive; they hold a sequence of char
values, and there are a bunch of functions in the standard library that treat them like strings. But they're not like C++ std::string
. They're just arrays.
int x[4] = { 1, 2, 3, 4 };
int y[4] = x; // illegal, arrays aren't automatically copied
Same thing for an array of char
:
char x1[4] = { 'a' , 'b', 'c', '\0' };
char y1[4] = x1; // illegal, arrays aren't automatically copied
The typical copy operation on an array of char
assumes that the sequence of characters is terminated by a nul character, and strcpy
looks for that:
char y1[4];
strcpy(y1, x1); // okay; copies the contents of x1 into y1
And there's a special rule for arrays that are initialized by a string literal:
char y2[4] = "abc"; // okay, copies string literal into y2, including nul terminator
The red herring in the question is the combination of a variable length array with an attempted initialization from another array. Variable length arrays are not part of C++, so char str[line.length()]
isn't legal. C allows runtime determination of array sizes, and some compilers allow this as an extension in C++.