After creating a char array of size 5, then I use strcpy
to fill the contents of the array but with a string larger than the original size; then I use puts()
to display the contents of the array an the whole string is displayed which is odd because I iterate through the array contents and it doesn't seems to me that the contents are stored in memory (but they are displayed). This is the code I am testing
#include <stdio.h>
#include <string.h>
int main(){
char str1[5];
int i = 0;
strcpy(str1,"Hello world");
puts(str1);
printf("Size of str1: %d\n",sizeof(str1));
for(i = 0;i < 15; i++){
printf("%c",str1[i]);
}
puts(""); // Blank space
puts(str1); // Display contents again... Different result!
return 0;
}
Output:
Hello world
Size of str1: 5
Hello ld [
Hello
The 3rd line in the output is the actual contents in memory (I iterated further to verify).
I wouldn't expect the first puts(str1)
to display the whole phrase but it does, also after displaying the contents I repeat puts(str1)
and the output changes which seems random to me, also the array size is only 5.
Could you help me figure out what is going on?