Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 在while循环中同时使用isalpha和toupper可以得到;“索引超出范围”;_C_Arrays_While Loop_Indexoutofboundsexception - Fatal编程技术网

C 在while循环中同时使用isalpha和toupper可以得到;“索引超出范围”;

C 在while循环中同时使用isalpha和toupper可以得到;“索引超出范围”;,c,arrays,while-loop,indexoutofboundsexception,C,Arrays,While Loop,Indexoutofboundsexception,这是给出错误的代码。“类型'int[26]'的索引-65超出范围” 如果我把它改成这个 char x; int a[26] = {0}; printf("Enter first word: "); while ((x=((toupper(getchar()))) != '\n') if (isalpha(x)) { a[x-'A']++ ; } 它的行为符合要求,错误消失了。 在第一个导致错误的错误中,我做错了什么?错误消息显示索引-65,因此A[x

这是给出错误的代码。
“类型'int[26]'的索引-65超出范围”

如果我把它改成这个

char x;
int a[26] = {0};

printf("Enter first word: ");
while ((x=((toupper(getchar()))) != '\n')

    if (isalpha(x))
    {
        a[x-'A']++ ;
    }
它的行为符合要求,错误消失了。
在第一个导致错误的错误中,我做错了什么?

错误消息显示
索引-65
,因此
A[x-'A']
中的
x-'A'
必须是-65。
'A'
的ASCII值为65,表示
x-65=-65
,解析为
x=0

为什么
x=0

因为
x
isalpha
的结果,它返回一个布尔值。特别是,对于false,它返回
0

此外,将此布尔值与
'\n'
进行比较也没有意义

你是说

while (isalpha(x = toupper(getchar())))
?


但是请注意,您的代码不能正确处理
EOF
EOF
不是
char
,这就是
getchar
返回
int
的原因。将其结果指定给
x
会丢失信息。

好的,我已经按照你说的做了。但是为什么要删除toupper和isalpha标签呢?他们是否误导了?认为 IsAlpal可能返回布尔值(1或0,尽管1可以是任何非零值)。当你从中减去26,你会得到一个负值。作为数组索引的负值不是一个好符号…您可能还需要考虑在哪个世界
isalpha(anything)
可能等于
'\n'
isalpha
为“true”生成的值可能是任何非零整数
while (isalpha(x = toupper(getchar())))