我有一个包含 15 个元素的数组,在每次 while 循环传递时,最后一个值被更改或者至少它明显是错误的。有时它会递增,有时它可能只是在程序的控制下跳转到另一个内存地址值。首先,我将所有值归零。代码:
int w16 = 0;
int len[15];
for (i = 0; i < 16; ++i){ //zero the array
len[i] = 0;
}
while ((c = fgetc(file)) != EOF) {
printf("while: %d \n", len[15]);
if(isspace(c)){
word = 0;
if (0 < letters && letters < 16){
len[letters] = len[letters] + 1;
letters = 0;
} else if(letters > 15){
++w16;
letters = 0;
}
}else if (word == 0) {
word = 1;
++letters;
++nw;
} else if (word == 1) {
++letters;
}
}
printf 命令的一些输出。我看不出它在上面的代码中有什么变化,为什么只有最后一个,其他的都很好:
while: 111
while: 110
while: 101
while: 32
while: 49
while: 50
while: 51
while: 52
while: 53
while: 54
while: 55
while: 56
while: 57
while: 115
Before fclose: -1
关于这里可能有什么问题的任何想法?除了这个讨厌的错误,其他一切都很好。我最近从 Java 转到 C,我也可能遗漏了一些东西。
最佳答案
int len[15];
这声明了一个包含 15 个元素的数组。它们的索引从 0
到 14
。
越界访问数组是未定义行为。确保您永远不会访问 len[15]
或更长时间。或者,如果您需要 16 个元素,请将其设为 int len[16]
。
另一种方式,如果您需要访问 elem 1-15
,您可以声明一个包含 16 个元素的数组并忽略第一个元素(索引 0
)。尽管如果您不习惯零索引数组,这可能是最简单的方法,但我不会推荐它,因为几乎所有编程语言都使用零索引数组,迟早您将不得不绕过这个问题。参见 Why are zero-based arrays the norm?
关于c - 数组的最后一个元素不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33598626/