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

前端 未结 6 1511
礼貌的吻别
礼貌的吻别 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 08:47

    The statement char * f = "abcdef" assigns a point in memory to the literal string "abcdef", however it will refuse to let you modify its contents until the memory is dynamically allocated - it's equivalent to a const char.
    All you're doing is creating a pointer in memory and then writing over the next 6 bytes, which is illegal in C.

提交回复
热议问题