C++ - char* vs. string*

前端 未结 7 1529
清歌不尽
清歌不尽 2021-02-04 03:28

If I have a pointer that points to a string variable array of chars, is there a difference between typing:

char *name = \"name\";

7条回答
  •  别那么骄傲
    2021-02-04 03:35

    Yes, there’s a difference. Mainly because you can modify your string but you cannot modify your first version – but the C++ compiler won’t even warn you that this is forbidden if you try.

    So always use the second version.

    If you need to use a char pointer for whatever reason, make it const:

    char const* str = "name";
    

    Now, if you try to modify the contents of str, the compiler will forbid this (correctly). You should also push the warning level of your compiler up a notch: then it will warn that your first code (i.e. char* str = "name") is legal but deprecated.

提交回复
热议问题