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

前端 未结 7 1547
礼貌的吻别
礼貌的吻别 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 01:54

    The reason is that when you declare a pointer, it doesn't actually point to anything useful. strcpy requires a block of memory for the string to be copied into. It will not do this for you automatically.

    From the documentation (emphasis mine):

    Copies the C string pointed by source into the array pointed by destination, including the terminating null character.

    To avoid overflows, the size of the array pointed by destination shall be long enough to contain the same C string as source (including the terminating null character), and should not overlap in memory with source.

    You need to make this true, as it is a precondition of the function.

    Also, in the parameters section:

    destination

    Pointer to the destination array where the content is to be copied.
    

    You need to make sure destination is a pointer to an array.

提交回复
热议问题