#include <iostream>
#include <string.h>
int main()
{
char bla[2][4];
strcpy(bla[0],"haha");
strcpy(bla[1],"hihi");
strcpy(bla[2],"huhu");
printf("%s",bla[0]);
return 0;
}
My question is, that why does it print out hahahihihuhu / all the strings I added to different indexes?
5 characters (do not forget the terminating zero of the string literal) is copied to bla[0] that has type char[4]. So the fifth character that is '\0' will be copyed in bla[1][0].
Here
strcpy(bla[1],"hihi");
is the same problem. Only the bla[1][0] that contains '\0' will be overwritten by the first character of the string literal. The terminating zero will be written beyond the array.
Here
strcpy(bla[2],"huhu");
you are overwriting the memory that does not belong to the array because the array has acceptable indexes in the range [0, 1].. Again you are overwriting the last terminating zero of the previous operastion.
So you get one long string which occupies the memory beyond the array. The type of the expression b[0] is char[]. So then you use
The program is invalid, the array size is too small.
String "haha" is five characters long.
It is equivalent to { 'h', 'a', 'h', 'a', '\0' }
Thus the terminating null character '\0' falls in the first position of the next string.
Each strcpy will over-write the null byte of the previous string.
The null of strcpy(bla[1],"hihi"); will fall outside boundaries of the array.
In addition, bla[2] is the third entry in an array of just two elements, so it as writing to an area outside the array.
If you want predictable and valid results, change line 7 to read: char bla[3][5];