gpt4 book ai didi

C编程警告: array subscript has type 'char' [-Wchar-subscripts]

转载 作者:太空宇宙 更新时间:2023-11-04 00:24:57 27 4
gpt4 key购买 nike

我似乎无法解决这个问题。下面是我的代码:

#include<stdio.h>
#include<ctype.h>
#include<string.h>

_Bool are_anagrams (const char *word1, const char *word2);

int main (void)
{
char an1[30], an2[30];
int j;
printf("Enter first word: ");
scanf("%s", an1);
printf("Enter second word: ");
scanf("%s", an2);
printf("The words are");

j = are_anagrams (an1, an2);

if (j == 0)
{
printf(" not anagrams. \n");
}else
printf(" anagrams. \n");

return 0;
}

_Bool are_anagrams (const char *word1, const char *word2)
{
int i;
int check[26] = {0};
for(i=0; i<30; i++)
if(word1[i] == '\0')
i=40;
else
{
word1[i] = toupper(word1[i]);
check[word1[i]-65]++;
}

for(i=0; i<30; i++)
if(word2[i] == '\0')
i=40;
else
{
word2[i] = toupper(word2[i]);
check[word2[i]-65]--;
}

for(i=0; i<26; i++)
if(check[i] != 0)
{
return 0;
}

return 1;
}

这些是错误信息:

anagram1.c:38:3: warning: array subscript has type ‘char’ [-Wchar-subscripts]
word1[i] = toupper(word1[i]);
^
anagram1.c:38:3: error: assignment of read-only location ‘*(word1 + (sizetype)((long unsigned int)i * 1ul))’
anagram1.c:46:4: warning: array subscript has type ‘char’ [-Wchar-subscripts]
word2[i] = toupper(word2[i]);
^
anagram1.c:46:4: error: assignment of read-only location ‘*(word2 + (sizetype)((long unsigned int)i * 1ul))’

最佳答案

警告:

warning: array subscript has type ‘char’

是“toupper()”需要“int”类型作为参数的结果,而问题代码提供的是“char”类型。

word1[i] = toupper(word1[i]);
...
word2[i] = toupper(word2[i]);

要消除警告,给 toupper() 'int' 值:

word1[i] = toupper((unsigned char)word1[i]);
...
word2[i] = toupper((unsigned char)word2[i]);

为了彻底,您可以将“toupper()”返回的值从“int”转换回“char”:

word1[i] = (char)toupper((unsigned char)word1[i]);
...
word2[i] = (char)toupper((unsigned char)word2[i]);

错误:

error: assignment of read-only location

是尝试使用“const”标志修改值的结果:

_Bool are_anagrams (const char *word1, const char *word2)

如果合适,您可以通过消除“const”标志来消除错误:

_Bool are_anagrams (char *word1, char *word2)

或者,您可以制作“const”字符串的本地工作副本:

_Bool are_anagrams (const char *I__word1, const char *I__word2)
{
int rCode = 0;
int i;
int check[26] = {0};
char *word1 = strdup(I__word1);
char *word2 = strdup(I__word2);

for(i=0; i<30; i++)
if(word1[i] == '\0')
i=40;
else
{
word1[i] = toupper(word1[i]);
check[word1[i]-65]++;
}

for(i=0; i<30; i++)
if(word2[i] == '\0')
i=40;
else
{
word2[i] = toupper(word2[i]);
check[word2[i]-65]--;
}

for(i=0; i<26; i++)
if(check[i] != 0)
goto CLEANUP;

rCode=1;

CLEANUP:
free(word2);
free(word1);

return(rCode);
}

注意:以上代码使用问题代码正文,可能准确也可能不准确。本回答无意修复问题代码中的其他问题;只是为了演示通过创建参数的非“const”副本来绕过参数上的“const”标志的正确方法

关于C编程警告: array subscript has type 'char' [-Wchar-subscripts],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23506902/

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