There are two problems -
First is that you cannot assign a single character value to an entire
char[] array.
Second is that arrays and characters are completely different things which have completely different (and fairly incompatible) rules in how you're allowed to use them.
where
char str_list[5][5]
represents an array-of-arrays
str_list[0]
represents a complete array of 5 characters.
Since you can't assign a single character to an entire array, the C++ compiler doesn't understand what you're trying to do when you write
str_list[0] = 'a';
Just to further compound your problems, arrays in C and C++ are not copyable using the
=
operator (This is partly for historical reasons).
- Therefore it would also be illegal to do this too:
str_list[0] = "hi";
What I expect your book is alluding to is that you can use
str_list[i]
in order to pass a string around to various string-handling functions or objects such as cout. e.g.
1 2 3 4
|
for( int i = 0; i < 5; ++i )
{
cout << str_list[i] << endl;
}
|
The reason this code works is that
cout <<
recognises char arrays as a special case and knows how to step through each individual character to output the entire string without you needing to do that yourself - However this is a feature of the C++ iostream library, and not specifically a C++ 'language' feature
The short of it is that you need to jump through a few hoops in order to use arrays in code you write from scratch. This is one of the reasons that C++ replaces char arrays with its own string type - because the way strings are handled in the old C language is very unintuitive (and error-prone).
See the example above by
Athar. You should have a much easier time using C++ strings, because you can treat C++ strings roughtly in the same way that you might treat an int or a char. (Strings are also resizable and know their own size - so no more "magic numbers")
If your book is telling you to use char arrays, then you may be suffering from an outdated book which had originally been written back in the 80s or 90s (C++ became a different language in 1998, and there are many books still around today which haven't been properly updated since then, so there's plenty of bad information/examples flying around unfortunately.)