0

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
user3484582
  • 557
  • 1
  • 6
  • 22

3 Answers3

4

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

Graeme Perrow
  • 56,086
  • 21
  • 82
  • 121
4

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]);
haccks
  • 104,019
  • 25
  • 176
  • 264
  • You are lucky that `"OKAY"` only contains characters from the basic character set. If it didn’t, the program would lead to *undefined behavior*. See any good documentation of `tolower` for the reason. – Roland Illig Jan 04 '15 at 22:10
  • @RolandIllig; Yeah, I know :) – haccks Jan 04 '15 at 22:31
1
char s[] = "OKAY";

for (int i = 0; i < 4; i++)
    s[i]=tolower(s[i]);
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70