gpt4 book ai didi

从 C 文件更改头文件中结构变量中的 char 数组会弄乱数组

转载 作者:太空宇宙 更新时间:2023-11-04 08:22:30 24 4
gpt4 key购买 nike

我有一个普通的 .c 文件,还有一个 .h 头文件。

这是我的 .c 文件代码的一部分,其中的注释解释了每一步的输出结果。这是在主要功能中:

FreqType freq;

freq.andLiteral[0] = 'a';
freq.andLiteral[1] = 'n';
freq.andLiteral[2] = 'd';
freq.andLiteral[3] = '\0';

printf("%s\n", freq.andLiteral); //Outputs: and

freq.theLiteral[0] = 't';
printf("%s, ", freq.theLiteral); printf("%s\n", freq.andLiteral); //Outputs: t, and
freq.theLiteral[1] = 'h';
printf("%s, ", freq.theLiteral); printf("%s\n", freq.andLiteral); //Outputs: th, and
freq.theLiteral[2] = 'e';
printf("%s, ", freq.theLiteral); printf("%s\n", freq.andLiteral); //Outputs: the, and
freq.theLiteral[3] = '\0';
printf("%s, ", freq.theLiteral); printf("%s\n", freq.andLiteral); //Outputs: the, and

freq.ofLiteral[0] = 'o';
printf("%s, ", freq.ofLiteral); printf("%s, ", freq.theLiteral); printf("%s\n", freq.andLiteral);
//Outputs: o, theo, and
freq.ofLiteral[1] = 'f';
printf("%s, ", freq.ofLiteral); printf("%s, ", freq.theLiteral); printf("%s\n", freq.andLiteral);
//Outputs: ofand, theofand, and
freq.ofLiteral[2] = '\0';
printf("%s, ", freq.ofLiteral); printf("%s, ", freq.theLiteral); printf("%s\n", freq.andLiteral);
//Outputs: of, theof,

这是我的 .h 头文件的相关部分:

typedef struct {
char theLiteral[3];
char ofLiteral [2];
char andLiteral [3];
int theCounter, ofCounter, andCounter;
} FreqType;

更改数组往往会相互混合的数组会出现什么问题?

最佳答案

您的字段声明太小。例如,theLiteral 需要允许 4 个字符,包括末尾的\0,因此您需要编写

char theLiteral[4]

等等。

关于从 C 文件更改头文件中结构变量中的 char 数组会弄乱数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32832446/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com