Do these statements about pointers have the same effect?

后端 未结 4 1153
梦毁少年i
梦毁少年i 2020-11-27 05:59

Does this...

char* myString = \"hello\";

... have the same effect as this?

char actualString[] = \"hello\";
char* myString          


        
4条回答
  •  清歌不尽
    2020-11-27 06:01

    It isn't the same, because the unnamed array pointed to by myString in the first example is read-only and has static storage duration, whereas the named array in the second example is writeable and has automatic storage duration.

    On the other hand, this is closer to being equivalent:

    static const char actualString[] = "hello";
    char* myString = (char *)actualString;
    

    It's still not quite the same though, because the unnamed arrays created by string literals are not guaranteed to be unique, whereas explicit arrays are. So in the following example:

    static const char string_a[] = "hello";
    static const char string_b[] = "hello";
    const char *ptr_a = string_a;
    const char *ptr_b = string_b;
    const char *ptr_c = "hello";
    const char *ptr_d = "hello";
    

    ptr_a and ptr_b are guaranteed to compare unequal, whereas ptr_c and ptr_d may be either equal or unequal - both are valid.

提交回复
热议问题