Program aborts when using strcpy on a char pointer? (Works fine on char array)

前端 未结 6 1512
礼貌的吻别
礼貌的吻别 2021-01-02 08:23

I\'m perplexed as to why the following doesn\'t work:

char * f = \"abcdef\";
strcpy(f, \"abcdef\");
printf(\"%s\",f);

char s[] = \"ffffd\";
strcpy(&s[0],          


        
6条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-02 09:00

    String literals are considered readonly by most compilers, so the memory where they reside can be marked as readonly, resulting in a runtime error.

    To make it work, do the following:

    char * f = strdup("abcdef");
    strcpy(f, "abcdef");
    printf("%s",f);
    free(f);
    

    This creates a modifiable copy of the string in the heap memory, which needs to get freed at the end of your program of course.

提交回复
热议问题