在学习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;
}
输出产生“大鱼小鱼”输出
但是当我重写最上面的代码并更改char catfish [9]时;烧char鱼[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;
}
预先感谢您对这个令人困惑的错误的解答
在catfish[9]
strcpy时,您没有为null终止符留出足够的空间"Big Fish\n"
。该字符串的长度为9个字符,这意味着您需要一个大小为10的缓冲区来存储空终止符。
如果字符串缺少空终止符,则输出将具有不确定的行为,因为程序无法知道字符串的结尾。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句