C function to capitalize first letter of words in an array

4reel77 picture 4reel77 · Nov 17, 2013 · Viewed 36.3k times · Source

I'm pretty new to C and am hitting a wall when creating the below function. I want to use this function to make the first letter of a word upper case for a static character array (char string[]. It looks ok to my eye, but I'm getting some syntax errors which are probably pretty basic. compiler errors:

error: invalid conversion from const char' toconst char*' initializing argument 1 of `size_t strlen(const char*)' assignment of read-only location

  void Cap(char string[]){
    int i;
    int x = strlen(string);
    for (i=1;i<x;i++){
         if (isalpha(string[i]) && string[i-1] == ' '){
         // only first letters of a word.
             string[i]= toupper(string[i]);
         }if (isalpha(string[0]))
                        {
                          string[0]=toupper(string[0]);
                        }
         }
}

Answer

ordahan picture ordahan · Nov 17, 2013

you might want to run strlen(string) - as strlen(string[i]) is trying to get the length of a single char.