在我学习C的过程中,我决定创建一个结构体(struct),以便能够提供其中鱼的大小。我的问题是,为什么当我写下这段小代码时:
#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;
}
输出结果为 "Big Fish Small Fish"。请查看这里。
但是,当我重新编写顶部代码并将char catfish [9];更改为char catfish [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;
}
它生成了“大鱼”。在这里查看输出
感谢提前解答这个困惑的错误。