Search code examples
ctolower

function tolower() not converting


What is wrong with this piece of code? I can't find out what's going on.

#include <stdio.h>
#include <ctype.h>

int main(void)
{
    char *s = "OKAY";

    for (int i = 0; i < 4; i++)
        tolower(s[i]);

    printf("\n%s\n", s);

    return 0;
}

Output:

OKAY

Solution

  • You need to assign the return value of tolower to s but this will invoke undefined behavior because string literals are non-modifiable as they are placed on read only section of memory. You can't modify it. Try this instead

    char s[]= "OKAY";
    for (int i = 0; i < 4; i++)
        s[i] = tolower(s[i]);