What is the difference between char a[] = ?string?; and char *p = ?string?;?

前端 未结 8 1026
太阳男子
太阳男子 2020-11-22 07:43

As the heading says, What is the difference between

char a[] = ?string?; and 
char *p = ?string?;  

This question was asked to me in inter

8条回答
  •  花落未央
    2020-11-22 08:21

    They do differ as to where the memory is stored. Ideally the second one should use const char *.

    The first one

    char buf[] = "hello";
    

    creates an automatic buffer big enough to hold the characters and copies them in (including the null terminator).

    The second one

    const char * buf = "hello";
    

    should use const and simply creates a pointer that points at memory usually stored in static space where it is illegal to modify it.

    The converse (of the fact you can modify the first safely and not the second) is that it is safe to return the second pointer from a function, but not the first. This is because the second one will remain a valid memory pointer outside the scope of the function, the first will not.

    const char * sayHello()
    {
         const char * buf = "hello";
         return buf; // valid
    }
    
    const char * sayHelloBroken()
    {
         char buf[] = "hello";
         return buf; // invalid
    }
    

提交回复
热议问题