0

In a C program, suppose I have a char array and a char pointer.

1.

char word[6] = "HELLO";
word[1] = 'A';

2.

char * word = "HELLO";
word[1] = 'A';

Why cant't we update the word using the 2nd method but can with 1st?

Note: Using 2nd method, though the program compiles there is a

Segmentation fault

error.

5
  • Because in the second example you are trying to modify a "string literal" which is read-only. Commented Feb 28, 2020 at 17:35
  • 1
    Does this answer your question? String literals: pointer vs. char array Commented Feb 28, 2020 at 17:35
  • 1
    Please seeWhy Can I not modify a string literal in c? Commented Feb 28, 2020 at 17:37
  • Closing with another duplicate. Commented Feb 28, 2020 at 17:38
  • @UnholySheep Thanks a lot. Excellent suggestion. Commented Feb 28, 2020 at 17:39

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.