-3

Why these two code snippets have different behaviors

char p[] = "hello";
p[0] = 'W'; //works fine

While this gives a segmentation fault

char *ptr = "hello"; 
ptr[0] = 'W'; // undefined behavior

What is the difference between both codes,why i am unable to modify the string using pointer?

Rajeev Singh
  • 3,292
  • 2
  • 19
  • 30
  • The first one does not modify a literal. It modifies array `p` which you formed by copying a literal. โ€“ M.M Apr 14 '16 at 08:00
  • You can add [**this question**](http://stackoverflow.com/questions/1704407/what-is-the-difference-between-char-s-and-char-s-in-c) to the duplicates of this question. โ€“ WhozCraig Apr 14 '16 at 08:01
  • or this one http://stackoverflow.com/questions/1011455/is-it-possible-to-modify-a-string-of-char-in-c โ€“ Thirupathi Thangavel Apr 14 '16 at 08:03

2 Answers2

2

In your second case,

char *ptr = "hello"; 

ptr points to a string literal. You cannot modify the content of a string literal. Period. It invokes undefined behavior.

Quoting C11, chapter ยง6.4.5, String literals

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

In contrast, first case is creating an array and initializing using that a string literal. The array is perfectly modifiable. You're good to go.

mch
  • 9,424
  • 2
  • 28
  • 42
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
2

The first code initialized an array and modifying its element is completely legal because the array is not const and p[0] is a valid index.

The second code is modifying string literals pointed by the pointer. It will invoke undefined behavior.

Quote from N1570 6.4.5 String literals:

7 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70