Why Can't we copy a string to Character Pointer WHEN we can assign a string directly to it?

前端 未结 7 1566
礼貌的吻别
礼貌的吻别 2021-02-10 01:16

This code produces \"p = hello world\":

#include \"stdio.h\"
#include \"string.h\"

int main(){
    char *p;
    p=\"hello world\";
    printf(\"p is %s \\n\",p)         


        
7条回答
  •  情歌与酒
    2021-02-10 02:15

    There are two distinct parts to memory copying. The first is the memory occupied by the item you want to copy (which you create in your example using the malloc() function), and the second is a pointer to that block of memory (which you call p). These two entities must be set up for the destination too, before you can do a copy. In your first example that fails, you have not set up the memory block for the destination (but it has been set for the source implicitly when you declare the string hello).

提交回复
热议问题