Tarjei Romtveit wrote:
> If i declare a char string like this:
>
> char szString[5] = "Hello";
>
> The content of the szString array is now somthing similar to this:
> szString[0] == H, szString[1] == e.. and so on, until szString[5] ==
> \0. (right?)
Close, but no.
char s[5];
will make an array of char with five (5) elements. The first index is
zero (0) and the last index is four (4). 0, 1, 2, 3, and 4 are five
seperate digits.
"Hello" including the final trailing '/0' is six chars. So you're off by
one.
>
> But my compiler returns a following error:
>
> "initializer-string for array of chars is too long"
>
> If i do the declartaion like this
>
> char szString[6] = "Hello";
>
> it compiles correctly.
Sure.
char s[6] = "Hello";
Six elements in the array named s. Valid indicies inclusive range from
zero to five.
Maybe better to write:
const char szString[] = "Hello";
Because I do so hate to count the number of characters in a string. I
often get it wrong and it just leads to headaches later should I want
the string to contain something else like "Goodbye".
or even better, perhaps,
#include <string>
..
..
..
const std::string sHello = "Hello";
> If I choose to write something on the screen
> like:
>
> cout << szString[6] << endl;
>
> It outputs a strange symbol that often differs (Probably something in
> the memory).
Because char x[6] has six valid indicies inclusive 0 to 5. 6 is one past
the last valid index. Who knows what's there?
Try this little bit of code:
----------
#include <iostream>
int main() {
std::cout << sizeof("Hello") << std::endl;
}
----------
>
> The 'cout << szString << endl;' ouputs Hello.
>
> Is there something wrong with my compiler?
It's hard to tell from just this simple case. Continue with your
testing and you're bound to eventually find a bug.
> Or is my logical talent
> really that bad?
>
> (I'm a beginner so bear with me)
For some people the idea that arrays in C++ have zero as their first
index can be a bit of a stumbling block. Get up, dust yourself off and
carry on.
BTW, if you don't mind, could you tell us what book you're using? Or are
you taking a course?
LR