gpt4 book ai didi

c - 将未初始化的数组计数增加到 4195520,C

转载 作者:行者123 更新时间:2023-11-30 18:42:06 26 4
gpt4 key购买 nike

在下面的示例中,我想了解为什么将值 4195520 添加到 chars[2](计算空格)。

char input;
int chars[4]; // [0] = newlines; [1] = tabs; [2] = spaces; [3] = all_else
int i, j;

printf("--\n");
printf("please enter input\n");
printf("~[enter] to end\n\n");
while ((input = getchar()) != EOF) {
if (input == '\n') {++chars[0];}
else if (input == '\t') {++chars[1];}
else if (input == ' ') {++chars[2];} // 4195520 is added (plus the amount of actual spaces), but only if I add to an array member
// if I increment an integer variable, it counts correctly
else if (input == '~') {printf("\n"); break;}
else {++chars[3];}
}

printf("--\n");
printf("the frequency of different characters\n");
printf("each dot represents one occurance\n");
for (i=0; i<=3; ++i) {
if (i == 0) {printf("newlines:\t");}
else if (i == 1) {printf("tabs:\t\t");}
else if (i == 2) {printf("spaces:\t\t");}
else if (i == 3) {printf("all else:\t");}
for (j=0; j<chars[i]; ++j) {printf(".");} // ~4.2 million dots are printed for spaces
printf("\n");
}

正确计数的解决方案是将数组成员初始化为 0,但我想了解为什么只有空格以及为什么只使用数组成员作为计数器,每次都会递增到数字 4195520。

最佳答案

它是垃圾值:由于先前的操作而恰好位于特定内存位置的某些值,并且尚未被清除。这次您可能会得到 4195520,但如果您运行其他程序然后重新运行代码,您可能会看到不同的结果。您几乎肯定会在不同的机器上看到不同的东西。

正如您所注意到的,正确的计数方法是这样的:

int chars[4] = {0};

关于c - 将未初始化的数组计数增加到 4195520,C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18449849/

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