function tolower() not converting

406 Views Asked by At

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
3

There are 3 best solutions below

2
On BEST ANSWER

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]);
0
On

The tolower function returns the lowercase equivalent of the input character. It doesn't modify it in place.

2
On
char s[] = "OKAY";

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