我试图在C中编写一个程序,该程序将读取用户输入的单词,并输出一个单词是否包含任何重复的字母,并将其计算
我编写了这段代码来尝试读取单词中是否有重复的字母,但我不断遇到此错误:
error: array subscript has type 'char' [-Werror=char-subscripts]
有问题的行是第 16 行" count[str[i]]++; "
代码如下:
# include <stdio.h>
# include <stdlib.h>
#include <string.h>
#define NO_OF_CHARS 256
void fillCharCounts(char *str, int *count)
{
int i;
for (i = 0; *(str+i); i++)
count[str[i]]++;
}
void printDups(char *str)
{
int *count = (int *)calloc(NO_OF_CHARS,
sizeof(int));
fillCharCounts(str, count);
int i;
for (i = 0; i < NO_OF_CHARS; i++)
if(count[i] > 1)
printf("%c, count = %d \n", i, count[i]);
free(count);
}
int main()
{
char word[100];
printf("Enter a word>\n");
scanf("%s", word);
char str[] = "%s";
printDups(str);
getchar();
return 0;
}
这是编译器给出的错误我。 任何帮助将不胜感激:)
Ive written this code to try and read if there are any duplicate letters in a word, but I keep coming across this error:
error: array subscript has type 'char' [-Werror=char-subscripts]
The line in question is line 16 " count[str[i]]++; "
Heres the code:
# include <stdio.h>
# include <stdlib.h>
#include <string.h>
#define NO_OF_CHARS 256
void fillCharCounts(char *str, int *count)
{
int i;
for (i = 0; *(str+i); i++)
count[str[i]]++;
}
void printDups(char *str)
{
int *count = (int *)calloc(NO_OF_CHARS,
sizeof(int));
fillCharCounts(str, count);
int i;
for (i = 0; i < NO_OF_CHARS; i++)
if(count[i] > 1)
printf("%c, count = %d \n", i, count[i]);
free(count);
}
int main()
{
char word[100];
printf("Enter a word>\n");
scanf("%s", word);
char str[] = "%s";
printDups(str);
getchar();
return 0;
}
This is the error that the compiler gives me.
Any help will be greatly appreciated :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
显示此警告是为了避免程序员传递负数组索引。您可以避免将索引设置为
unsigned int
或int
本身:This warning is shown to avoid the programmer of passing negative array indexes. You can avoid it seting the index to
unsigned int
orint
itself: