Small errors strings for use

These pits recent code review when came.

  A quick look at the code looks like no problem, a simple string comparison. But when you looked at the feeling something is wrong, the result is always run output "UTF-32". Here there is a misunderstanding that the string ( char *) is not directly comparable , the following code is an address string comparison, this will cause them to address the string never been output it is equal to "UTF-32" The results of the .

string str("gbk");
if (str.c_str() == "gbk")
    cout << "GBK";
else if (str.c_str() == "utf-8")
    cout << "UTF-8";
else if (str.c_str() == "utf-16")
    cout << "UTF-16";
else
    cout << "UTF-32";

The right approach:

  1. Direct use string comparison .
string str("gbk");
if (str == string("gbk"))
    cout << "GBK";
else if (str == string("utf-8"))
    cout << "UTF-8";
else if (str == string("utf-16"))
    cout << "UTF-16";
else
    cout << "UTF-32";
  1. Use strcmp function to compare strings .
string str("gbk");
if (strcmp(str.c_str(), "gbk") == 0)
    cout << "GBK";
else if (strcmp(str.c_str(), "utf-8") == 0)
    cout << "UTF-8";
else if (strcmp(str.c_str(), "utf-16") == 0)
    cout << "UTF-16";
else
    cout << "UTF-32";

  After following code runs directly segmentation fault, because the release of an invalid memory address (static memory). Fortunately in C ++ 11, will direct the compiler error.

char *str = (char *)malloc(32);
str = "Hello world!";
free(str);

The right approach (using strcpy string copy):

char *str = (char *)malloc(32);
strcpy(str, "Hello world!");
free(str);
Published 354 original articles · won praise 80 · Views 150,000 +

Guess you like

Origin blog.csdn.net/nicai_xiaoqinxi/article/details/103838962