let's say you want to store "cosmic" in the string strAstro.
Since you know 'cosmic' is exactly 6 characters long, you would be tempted to do this:
char strAstro[6];
Though the compiler accepts this, it is wrong.
Character strings are always stored with a null character ( '\0' ) appended
immediately where the string ends.
So let's say initially your array is declared to hold 10 characters:
1 2
|
char strAstro[10];
cin >> strAstro; //suppose the user will input cosmic here
|
Each element in array strAstro will be:
strAstro[0] : c
strAstro[1] : o
strAstro[2] : s
strAstro[3] : m
strAstro[4] : i
strAstro[5] : c
strAstro[6] : \0
strAstro[7] :
strAstro[8] :
strAstro[9] :
Now as you see, the last three bytes remain empty. This is alright as these bytes are reserved for that array (since you declared strAstro to be 10 elements long initially).
Note the presence of the terminating null character.
strlen() returns the number of characters in the array, excluding null character. So if we passed strAstro to it, it would return 6.
So if you know the exact number of characters that you want to store in your array (in our case 6 for cosmic), you should initialise an array of length
strlen(theString) + 1 (and thereby avoid the excess empty bytes as in the example above.
But suppose we had declared strAstro as:
1 2
|
char strAstro[6];
cin >> strAstro; //user inputs 'cosmic' here
|
The computer will store the first 6 bytes in the space allocated for the array like this:
1 2 3 4 5 6
|
strAstro[0] : c
strAstro[1] : o
strAstro[2] : s
strAstro[3] : m
strAstro[4] : i
strAstro[5] : c
|
But as we said, it will also append a null character. It will store the null character in the next consecutive byte, which may already contain data. Obviously this is not good.
Hope that helped ;)