Cannot modify C string

前端 未结 5 797
小蘑菇
小蘑菇 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:34

    Do:

     char * bar = strdup(foo);
     bar[5] = 'x';
    

    strdup makes a modifiable copy.

    And yes, you should really test that strdup didn't return NULL.

提交回复
热议问题