I was just wondering why the output for this code I have below is abcdef def instead of abc def.
main()
{
char array1[3]="abc";
array1[3]='\0';
char array2[3]="def";
array2[3]='\0';
printf("%s %s", array1, array2);
}
char array1[3]="abc";
array1[3]='\0';
char array2[3]="def";
array2[3]='\0';
array1[3]='\0'; and array2[3]='\0'; statements access arrays out of bounds and invoke undefined behavior. The last element of an array of 3 elements is array1[2] not array[3].
To fix your program, declare your arrays as:
char array1[]="abc";
char array2[]="def";
And don't manually add the null terminator as it will be already included in the declaration above.
EDIT:
some other answers incorrectly assume that
char array1[3]="abc";
would write a trailing null character outside the array. Actually no trailing null character is written in this initialization. The declaration is equivalent to:
char array1[3]= {'a', 'b', 'c'};
When you do:
char array1[3]="abc";
Then array1[3] is out of bounds.
You should do:
char array1[4]="abc"; //Remember the '\0'
^^^
Note that the '\0' will be added in this way.
Also please note that when you have array of size N, then the indexes are from 0 to N - 1.
\0 is added in char array1[3]="abc"; as the length of the string is the same as the size of the array,In your code
main()
{
char array1[3]="abc"; //Undefined ,when you access this using printf() with %s
array1[3]='\0'; //here you are storing value which is out of bound in nature
char array2[3]="def"; //same as above
array2[3]='\0'; //same as above
printf("%s %s", array1, array2);
}
memory:
---------------
| a | b | c |\0|
----------------
The last \0 what you are putting is more than the space you have allocated.
solution:
main()
{
char array1[4]="abc";
//array1[3]='\0'; //no need
char array2[4]="def";
// array2[3]='\0'; //no need
printf("%s %s", array1, array2);
}
It will give desired output
This is such a bad code! What is happening is the following:
Compiler allocated space for 2x3 chars.
main()
{
char array1[3]="abc"; //Will write "abc" in array 1 AND \0 in array2[0]
array1[3]='\0'; //Out of array!!! (Re)writing \0 in array2[0]
char array2[3]="def"; //Will write "def" in array2 AND \0 after array2 space, POTTENCIALLY corrupting code!
array2[3]='\0'; //\0 (re)wrote after array2, POTTENCIALLY corrupting code!
What you have in memory is 7 bytes (just 6 were allocated): "abcdef\0". Pointes still ok: array1 points "a" and array2 points "d". In C standard libraries, strings sizes are determined by ending zero terminator. So when you printf array1, it will read "abcdef" until \0.
'\0' is written. See the edit in my answer.
char array1[3+1]="abc";+1 for The end of the stringchar array1[3] = "abc";is not allowed in vs2008. I've tried that anderror C2117: 'array1' : array bounds overflowoccurred.