Search code examples
carraysstringpointersstring-literals

Why modifying a string with different ways have different behaviors?


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?


Solution

  • 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.