String Declaration

2020-04-21 01:44发布

String declaration works when I declare in the the following ways:

string a = "xyz";
char a[] = "xyz";

But in case of:

char *a = "xyz";

It gives an ERROR in g++ 4.9.2 compiler:

warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings] char *a = "xyz";

I think these three declaration types are different from each other. Please help me out.

2条回答
趁早两清
2楼-- · 2020-04-21 02:08

In earlier version(s) of the language, you could use:

char* a = "xyz";

Now, you must use:

char const* a = "xyz";

A string literal, such as "xyz" resides in the rea-only parts of the program. It can be used to initialize a char const* since you are not supposed to modify the contents of what a char const* points to. Using it to initialize a char* opens the possibility of a user modifying them accidentally. In addition, modifying such strings is cause for undefined behavior.

A string literal can also be used to initialize a char[]. In that case, the string literal is copied to the space allocated for the array. Hence, there is no risk of modifying read-only data of the program. Hence, using

char a[] = "xyz";

is OK.

The line

string a = "xyz";

invokes the constructor of string that takes a char const* and then uses that object to initialize a. Hence, that line is also OK.

查看更多
一纸荒年 Trace。
3楼-- · 2020-04-21 02:09
string a = "xyz";

This uses initializer syntax to invoke the constructor std::string( const char* ).

char a[] = "xyz";

This declares an array large enough to store the string plus terminator. It follows standard array-initializer rules. Think of it as equivalent to char a[] = { 'x', 'y', 'z', '\0' };

char *a = "xyz";

This takes a string literal ("xyz") and assigns it to a non-constant pointer. Within the language, such a pointer means it is okay to modify the string it points to, but that is undefined behaviour in this case, because string literals may not be modified. To prevent you from making such a mistake, the compiler gives you a warning. The following is valid and will not emit a warning:

const char *a = "xyz";
查看更多
登录 后发表回答