C++:警告:与字符串文字结果比较,未指定的行为[-Waddress]

时间:2021-02-16 16:38:06

I've started learning/using bits of C++, Ruby background.

我已经开始学习/使用c++、Ruby背景。

Can someone help me with the below code?

谁能帮我写下面的代码吗?

I have no idea what's wrong but it's causing this error message:

我不知道哪里出错了,但它导致了这个错误信息:

C++: warning: comparison with string literal results in unspecified behaviour [-Waddress]

C++:警告:与字符串文字结果比较,未指定的行为[-Waddress]

void OnUserConnect(LocalUser* user)
{
    if (user->MyClass->name.c_str() == "user") {
        ServerInstance->SNO->WriteToSnoMask('a', "Triggered: %s", user->MyClass->name.c_str());
    }
}

2 个解决方案

#1


3  

Your comparison user->MyClass->name.c_str() == "user" compares two pointers, and two pointers that will never be the same.

您的比较用户->MyClass->name.c_str() = "user"比较两个指针和两个永远不会相同的指针。

Since you seem to be using std::string you can use the equality comparison operator directly without needing to get a pointer:

由于您似乎在使用std::string,所以您可以直接使用相等比较运算符,而不需要获取指针:

if (user->MyClass->name == "user") { ... }

If for some strange reason you want to compare using C-style string pointers, you must use std::strcmp.

如果出于某种奇怪的原因,您希望使用c样式的字符串指针进行比较,那么必须使用std::strcmp。

#2


0  

You can't compare a char* variable and a const char* literal. if you want to use this comparison you must use strcmp function. You can replace the below condition to yours

不能比较char*变量和const char* literal。如果要使用这种比较,必须使用strcmp函数。您可以将以下条件替换为您的条件

if(!strcmp(user->MyClass->name.c_str(),"user")

#1


3  

Your comparison user->MyClass->name.c_str() == "user" compares two pointers, and two pointers that will never be the same.

您的比较用户->MyClass->name.c_str() = "user"比较两个指针和两个永远不会相同的指针。

Since you seem to be using std::string you can use the equality comparison operator directly without needing to get a pointer:

由于您似乎在使用std::string,所以您可以直接使用相等比较运算符,而不需要获取指针:

if (user->MyClass->name == "user") { ... }

If for some strange reason you want to compare using C-style string pointers, you must use std::strcmp.

如果出于某种奇怪的原因,您希望使用c样式的字符串指针进行比较,那么必须使用std::strcmp。

#2


0  

You can't compare a char* variable and a const char* literal. if you want to use this comparison you must use strcmp function. You can replace the below condition to yours

不能比较char*变量和const char* literal。如果要使用这种比较,必须使用strcmp函数。您可以将以下条件替换为您的条件

if(!strcmp(user->MyClass->name.c_str(),"user")