Pri*_*Key 3 c unix memory arrays struct
在我学习 CI 的过程中,我决定创建一个结构体来提供我在其中提供的鱼的大小,我的问题是为什么当我编写这段代码时:
#include <stdio.h>
#include <string.h>
struct fish
{
char catfish[9]; //reserve memory for 9 chars
char goldfish[10]; //reserve memory for 10 chars
char mackrel;
char oldfish;
};
int main()
{
struct fish typeof_fish;
strcpy(typeof_fish.catfish, "Big Fish\n");
strcpy(typeof_fish.goldfish, "Small Fish\n");
printf("%s\n", typeof_fish.catfish);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出产生“大鱼小鱼” 输出在这里
然而,当我重写最上面的一段代码并更改 char catfish[9] 时;烧焦鲶鱼[10]:
#include <stdio.h>
#include <string.h>
struct fish
{
char catfish[10]; //reserve memory for 10 chars
char goldfish[10]; //reserve memory for 10 chars
char mackrel;
char oldfish;
};
int main()
{
struct fish typeof_fish;
strcpy(typeof_fish.catfish, "Big Fish\n");
strcpy(typeof_fish.goldfish, "Small Fish\n");
printf("%s\n", typeof_fish.catfish);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
提前感谢您对这个令人费解的错误的回答
catfish[9]当您使用 strcpy 时,您没有为空终止符留出足够的空间"Big Fish\n"。该字符串有 9 个字符长,这意味着您需要一个大小为 10 的缓冲区来存储空终止符。
如果字符串错过了空终止符,则输出具有未定义的行为,因为程序无法知道字符串在哪里结束。