1
char *c = "H'eLo";
for (int i = 0; i < 5; i++)
{
    if (isupper(c[i]))
    {
        c[i] = tolower(c[i]);
        printf("%c \n", c[i]);
    }
}

So I am running this code, and trying to figure out what I am doing wrong. What is the reason for the segmentation fault?

JameNULL
  • 13
  • 2
  • 1
    Change `char *c = ...` to `char c[] = ...`. The reason the pointer version doesn't work is you have a pointer to a string constant, which cannot be modified. Changing it to a statically initialized array will fix it. – Tom Karzes Jun 09 '20 at 16:22
  • You make `c` point to a string constant. Then you try to modify the thing `c` points to. But, by definition, you can't modify a constant. – David Schwartz Jun 09 '20 at 22:31

1 Answers1

-1

If you want to modify the string, you should allocate it dinamically just like this

    char *c = malloc(5*sizeof(char));

Then, pass the string with strcpy

    strcpy(c, "H'eLo");

Or you also can do it with the function strdup, which is the easiest option

    char *c = strdup("H'eLo");

These examples should work, because C doesn't let you modify strings literals


Mapromu
  • 101
  • 4