gpt4 book ai didi

c - 具有此索引的数组如何工作? K&R练习

转载 作者:太空狗 更新时间:2023-10-29 15:31:33 25 4
gpt4 key购买 nike

我正在阅读 K&R,目前在第 1 章。阅读部分内容并尝试解决问题后,我喜欢在线查看其他解决方案,只是查看解决同一问题的不同方法。

练习 1-14 说我们需要打印输入中不同字符频率的直方图。我发现的这个解决方案只考虑了字母字符:

#include <stdio.h>

#define MAX 122
#define MIN 97
#define DIFF 32

int main(){
int c = EOF;
int i, j;
int array[MAX - MIN];
printf("%d ", MAX - MIN);

for (i = MIN; i <= MAX; i++){
array[i] = 0;
printf("%d ", i);
}

while ((c = getchar()) != EOF){
if (c >= MIN)
++array[c];
else {
++array[c + DIFF];
}
}

for (i = MIN; i <= MAX; i++){
printf("|%c%c|", i - DIFF, i);
for (j = 1; j <= array[i]; j++){
putchar('*');
}
putchar('\n');
}

return 0;
}

虽然我理解这段代码背后的逻辑,但我不明白 array[] 数组如何或为何工作。声明数组时,它的大小为 25 (MAX - MIN)。 该数组的索引应从 0 到 24。但是在第一个循环期间,数组使用 中的值进行索引97122。但是,如果索引从一个更大的值开始,怎么可能访问数组呢?循环不应该是

for (i = 0, i < MAX - MIN; i++)

我不明白如何从

索引数组
array[97] ... array[122]

编辑:

我自己在第一个循环中添加了 printf("%d ", MAX - MIN);printf("%d ", i); 来尝试查看它是否实际上是从 97 开始索引数组。

最佳答案

int array[MAX - MIN];

这里,数组的大小是25因为197-97 = 25 .

 for (i = MIN; i <= MAX; i++){
array[i] = 0;

在这里,array[i] 的索引超出范围,因为数组的大小是 25和值(value)和MIN97 .

此外,++array[c];j <= array[i];未定义,因为越界。

GCC 编译器生成警告:

source_file.c: In function ‘main’:
source_file.c:14:10: warning: array subscript is above array bounds [-Warray-bounds]
array[i] = 0;
^
source_file.c:20:12: warning: array subscript is above array bounds [-Warray-bounds]
++array[c];
^
source_file.c:20:12: warning: array subscript is above array bounds [-Warray-bounds]
source_file.c:28:27: warning: array subscript is above array bounds [-Warray-bounds]
for (j = 1; j <= array[i]; j++){
^

C11 J.2 未定义行为

  • Addition or subtraction of a pointer into, or just beyond, an array object and an integer type produces a result that points just beyond the array object and is used as the operand of a unary *operator that is evaluated (6.5.6).

  • An array subscript is out of range, even if an object is apparently accessible with the given subscript (as in the lvalue expression a[1][7] given the declaration int a[4][5]) (6.5.6).

关于c - 具有此索引的数组如何工作? K&R练习,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47089980/

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