【发布时间】:2014-05-07 00:49:48
【问题描述】:
我似乎无法解决这个问题。以下是我的代码:
#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))’
【问题讨论】:
-
word1和word2是指向const char的指针。 -
检查[toupper(word1[i])-65]++;检查[toupper(word2[i])-65]--;
-
我没有收到那个警告。我看到的唯一警告是你试图覆盖一个常量。
-
那些错误是可以理解的,但那些警告很疯狂,那些下标是
int,而不是char。 -
65这个数字有什么意义?我想我知道答案,但是有一种更清晰的方法来写它。提示:字符常量的类型为int。
标签: c arrays gcc char subscript