0

While learnng about pointer in C, I am getting Segmentation fault error in an online compiler because of changing value of a particular character of a stirng variable. I first tried it in my local compiler but it was printing nothing as output. What is the reason for the problem, and how can it be solved?

Code I write is :

#include <stdio.h>

int main(void)
{
    char *a = "abcd";
    a[0] = 'A';

    printf("%s\n",a);
    
}

Output of online compiler :

Segmentation fault

Output of offline compiler was nothing.

starball
  • 20,030
  • 7
  • 43
  • 238
  • Does the answer here help? https://stackoverflow.com/questions/164194/why-do-i-get-a-segmentation-fault-when-writing-to-a-char-s-initialized-with-a – EdmCoff Jan 06 '23 at 19:34
  • `a` is a pointer to a *string literal*. String literals can't be modified in C (attempting to do so is causing undefined behavior). – Eugene Sh. Jan 06 '23 at 19:34
  • Because `char *a = "abcd";` is a string literal. See: https://stackoverflow.com/questions/718477/string-literals – Gaurav Pathak Jan 06 '23 at 19:35

0 Answers0