'Im trying to write a program in C that will read a word entered by the user and output whether a word contains any duplicate letters, and tally them

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 :)



Solution 1:[1]

This warning is shown to avoid the programmer of passing negative array indexes. You can avoid it seting the index to unsigned int or int itself:

void fillCharCounts(char *str, int *count)
{

   int i;

   for (i = 0; *(str+i);  i++)

      count[(unsigned int)str[i]]++;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Matheus Delazeri