从C文件更改头文件中struct变量中的char数组会使数组混乱



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

这是我的。c文件代码的一部分,注释解释了每一步的输出是什么样子。这在main函数中:

FreqType freq;
    freq.andLiteral[0] = 'a';
    freq.andLiteral[1] = 'n';
    freq.andLiteral[2] = 'd';
    freq.andLiteral[3] = '';
    printf("%sn", freq.andLiteral); //Outputs: and
    freq.theLiteral[0] = 't';
    printf("%s, ", freq.theLiteral); printf("%sn", freq.andLiteral); //Outputs: t, and
    freq.theLiteral[1] = 'h';
    printf("%s, ", freq.theLiteral); printf("%sn", freq.andLiteral); //Outputs: th, and
    freq.theLiteral[2] = 'e';
    printf("%s, ", freq.theLiteral); printf("%sn", freq.andLiteral); //Outputs: the, and
    freq.theLiteral[3] = '';
    printf("%s, ", freq.theLiteral); printf("%sn", freq.andLiteral); //Outputs: the, and
    freq.ofLiteral[0] = 'o';
    printf("%s, ", freq.ofLiteral); printf("%s, ", freq.theLiteral); printf("%sn", freq.andLiteral);
    //Outputs: o, theo, and 
    freq.ofLiteral[1] = 'f';
    printf("%s, ", freq.ofLiteral); printf("%s, ", freq.theLiteral); printf("%sn", freq.andLiteral);
    //Outputs: ofand, theofand, and
    freq.ofLiteral[2] = '';
    printf("%s, ", freq.ofLiteral); printf("%s, ", freq.theLiteral); printf("%sn", freq.andLiteral);
    //Outputs: of, theof, 

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

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

改变数组会有什么问题,数组往往会相互混合?

您的字段声明太小了。例如,literal需要允许4个字符,包括末尾的,因此您需要写入

char theLiteral[4]

等等

最新更新