Cannot modify C string

前端 未结 5 786
小蘑菇
小蘑菇 2020-12-05 16:11

Consider the following code.

int main(void) {
    char * test = \"abcdefghijklmnopqrstuvwxyz\";
    test[5] = \'x\';
    printf(\"%s\\n\", test);
    return EXIT_         


        
5条回答
  •  死守一世寂寞
    2020-12-05 16:51

    Char pointers defined with an initialization value go into a read-only segment. To make them modifiable, you either need to create them on the heap (e.g. with new/malloc) or define them as an array.

    Not modifiable:

    char * foo = "abc";
    

    Modifiable:

    char foo[] = "abc";
    

提交回复
热议问题