1

In the following C program,'s' is declared as character pointer and assigned with a string "Fine", now I am trying to replace the first character to 'N' that should result in "Nine". But this program results in runtime error.

#include<stdio.h>

main()
{
   char *s = "Fine";
   *s = 'N';

   printf("%s", s);
}

whereas, if the above program is changed as following, declaring 's' as a character array, the program runs without any error and output will be "Nine"

#include<stdio.h>

main()
{
   char s[] = "Fine";
   *s = 'N';

   printf("%s", s);
}

I do not know the reason behind this issue. It would be great if someone explains me. Thanks in advance.

  • 1
    String literals are *read-only*: changing them invokes Undefined Behaviour. `char s[] = "Fine";` is the same as `char s[5]; s[0] = 'F'; s[1] = 'i'; s[2] = 'n'; s[3] = 'e'; s[4] = '\0';` – pmg May 22 '20 at 08:05
  • 1
    Yes, understood. Normally, string literals are stored in read-only memory when the program is run. This is to prevent one accidentally changing a string constant. In the first program, "Fine" is stored in read only memory and *s points to the first character. Run-time error occurs when one try to change the first character to 'N'. In the second program, the string is copied by the compiler from its read-only memory to s[] array. Then changing the first character is allowed. Also printing the size of the string s will show you that the compiler has allocated 5 bytes for it. – user13548680 May 22 '20 at 09:38

0 Answers0