0
#include <stdio.h>

void dosmth(char* ptr, char* arr);

int main() {
    char* ptr = "hello";
    char arr[] = "jumbo";

    dosmth(ptr, arr);
    return 0;
}

void dosmth(char* ptr, char* arr) {
    arr[0] = 'J';
    ptr[0] = 'H'; //works if line is commented out
    printf("%s\n", arr);
    printf("%s\n", ptr);
}

My understanding is that char* and char[] are different types. The former is a pointer to an array of characters. This initialization above creates a constant string literal that lives in the read-only part of the memory which cannot be changed at any time.

The latter is an incomplete array of a certain number of characters, but that can be changed.

However, I don't understand why, after the array has decayed to a pointer when passed as an argument, it is still possible to change for example arr[0], yet (as expected) not ptr[0]?

D-I-S-C
  • 79
  • 1
  • 6
  • [modifying a string literal is undefined behavior](https://www.wikiod.com/w/C_Undefined_behavior#Modify_string_literal). That doesn't mean C prevents you from doing it. It means from that point on, the behavior of the program is undefined. – yano Nov 05 '21 at 16:56
  • 1
    Does this answer your question? [Why do I get a segmentation fault when writing to a "char \*s" initialized with a string literal, but not "char s\[\]"?](https://stackoverflow.com/questions/164194/why-do-i-get-a-segmentation-fault-when-writing-to-a-char-s-initialized-with-a) –  Nov 05 '21 at 16:58
  • Specifically to your point, the array has its own storage which the literal is copied into, the pointer points to the literal itself in read-only memory. –  Nov 05 '21 at 17:00
  • Re “why, after the array has decayed to a pointer when passed as an argument, it is still possible to change for example arr[0], yet (as expected) not ptr[0]?”: The conversion of the array to a pointer merely means a pointer is passed to the function. That does not change the array the characters are stored in, nor does it change the characters in the string literal, nor does it change where they are stored nor whether they can be modified. – Eric Postpischil Nov 05 '21 at 17:15
  • Note that the type of `arr[]` becomes complete (i.e., its size is determined) at the end of the initializer. – Ian Abbott Nov 05 '21 at 17:19

0 Answers0