创建一个大小为5的char数组后,我strcpy用来填充数组的内容,但是字符串大于原始大小; 然后我puts()用来显示数组的内容,显示整个字符串,这是奇怪的,因为我遍历数组内容,我觉得内容不存储在内存中(但显示它们).这是我正在测试的代码
#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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
Hello world
Size of str1: 5
Hello ld [
Hello
Run Code Online (Sandbox Code Playgroud)
输出中的第3行是内存中的实际内容(我进一步迭代验证).
我不希望第一个puts(str1)显示整个短语,但它确实显示我重复的内容puts(str1)和输出更改,这对我来说似乎是随机的,数组大小也只有5.
你能帮我弄清楚发生了什么吗?