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

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

    Notice what the two working examples have in common: they have a p = line that assigns something to p. The non-working example does not do this.

    Consider this line (from the first example):

    p = "hello world";
    

    Although it might look like it's "copying a string to a char pointer", it's not. It's copying the location of a string to a pointer-to-char. That's what a pointer-to-char like p stores - the location of a contiguous block of chars.

    Similarly, consider this line from the third example:

    p = malloc(10);
    

    This is also copying a location - it's copying the location of a block of 10 unintialised chars into p.

    strcpy(dest, source) copies characters from the location given by source to the location given by dest. It should be clear that if you never set p to a valid location, then strcpy(p, "hello") can't do anything sensible - in your second example, p is an essentially random location, and you then ask strcpy() to copy something to that location.

提交回复
热议问题