Is it possible to modify a string of char in C?

前端 未结 9 1418
小蘑菇
小蘑菇 2020-11-22 09:08

I have been struggling for a few hours with all sorts of C tutorials and books related to pointers but what I really want to know is if it\'s possible to change a char point

9条回答
  •  广开言路
    2020-11-22 09:58

    It seems like your question has been answered but now you might wonder why char *a = "String" is stored in read-only memory. Well, it is actually left undefined by the c99 standard but most compilers choose to it this way for instances like:

    printf("Hello, World\n");
    

    c99 standard(pdf) [page 130, section 6.7.8]:

    The declaration:

    char s[] = "abc", t[3] = "abc";
    

    defines "plain" char array objects s and t whose elements are initialized with character string literals. This declaration is identical to char

    s[] = { 'a', 'b', 'c', '\0' }, t[] = { 'a', 'b', 'c' };
    

    The contents of the arrays are modifiable. On the other hand, the declaration

    char *p = "abc";
    

    defines p with type "pointer to char" and initializes it to point to an object with type "array of char" with length 4 whose elements are initialized with a character string literal. If an attempt is made to use p to modify the contents of the array, the behavior is undefined.

提交回复
热议问题