1

How do I update a single char in a string declared as char*?

I have tried this:

int main(void)
{
    char* s = "hello";
    s[0] = 'y';
    printf("%s\n", s);
    return 0;
}

This compiles without warnings or errors with GCC 4.8.1 (MinGW) using these parameters:

gcc -Wall -Wextra -Werror -o str.exe str.c

But when I run the application, it only prints a blank line?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
user966939
  • 692
  • 8
  • 27

1 Answers1

3

What you're doing is an attempt to modify a string literal. It results in undefined behavior.

Related, from the standard C11, chapter §6.4.5, String literals

[..] If the program attempts to modify such an array, the behavior is undefined.

You need to use an array of chars if you want to modify the contents, instead. Something along the line of

char s[] = "hello";

Otherwise, if you want to have the char *s form, you have to

  1. Allocate memory to s
  2. Use strcpy() to copy the content into s

and then, you can modify s, as the memory location returned by malloc() will be writable.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261