0

I wanted to make my own function that converts a string to lowercase,s and I want to be able to convert the result of tolower to a char but whenever I typecast it, it crashes. How would I fix this?

My function is as follows:

void stringToLower(char **str){
    char *val = *str;

    int i = 0;
    int n;

    for ( i = 0; val[i] != NULL; i++){
         val[i] = (char)(tolower(val[i]) );
         printf("%c", val[i]);
    }

    printf("\n");

    return;

}
int main(){


    char *name = "BILLY";
    stringToLower(&name);

    printf("%s", name);


    return 0;
}
Shinji-san
  • 971
  • 4
  • 14
  • 31
  • 1
    Have you tried turning on your compiler warnings? –  Mar 13 '18 at 02:49
  • 2
    The problem is that "BILLY" is probably landing in a read-only section of your executable. try replacing it's storage in `main` with `char name[100] = "BILLY";` – lockcmpxchg8b Mar 13 '18 at 02:51
  • 1
    And if you’re converting in-place, you can just pass a ‘char*’. char** is unnecessary unless you need to modify the actual pointer – zzxyz Mar 13 '18 at 02:54
  • There is no need for `char **str`, you simply want to pass a pointer to the string `char *str`, not the address of the string. – David C. Rankin Mar 13 '18 at 02:59

1 Answers1

0

You cannot modify a string defined via

char *name = "BILLY";

instead try

char name[] = "BILLY";

The first one is a pointer to a read-only string literal, the second defines a character array containing the string BILLY.

And there is no need to pass the address of name to stringToLower(), it is a pointer, and you can modify what it points to (the string characters).

void stringToLower(char *str) {
    int i = 0;

    for (i = 0; str[i] != NULL; i++) {
        str[i] = (char)(tolower(str[i]));
        printf("%c", str[i]);
    }
    printf("\n");

    return;
}

int main() {
    char name[] = "BILLY";

    stringToLower(name);

    printf("%s", name);

    return 0;
}
Stephen Docy
  • 4,738
  • 7
  • 18
  • 31