简体   繁体   English

C++ 是否将 char 指针视为 c 样式字符串?

[英]Does C++ treat char pointers as c style strings?

Does C++ treat char pointers as c-style strings? C++ 是否将 char 指针视为 c 样式字符串?

int main(int argc,char* argv[])
{
    if (argv[1] == "-d")
    {

    }
}

argv[1] contains a char pointer, how is the statement argv[1] == "-d" not causing the compiler to throw an error because "d" is a string whereas argv[1] is a pointer to a char value argv[1] 包含一个 char 指针,语句argv[1] == "-d"如何不会导致编译器抛出错误,因为"d"是一个字符串,而argv[1]是一个指向 char 值的指针

because "d" is a string whereas argv[1] is a pointer to a char value因为"d"是一个字符串,而argv[1]是一个指向char值的指针

That's where you're kind of wrong friend.那就是你有点错误的朋友。

argv[1] is in this case a char* like you said. argv[1]在这种情况下是一个char*就像你说的那样。

"-d" is a const char[3] ( -d plus the null terminator), this array can decay to a pointer which means == compiles. "-d"是一个const char[3] (- -d加上 null 终止符),这个数组可以衰减为一个指针,这意味着==编译。

As pointed out in the comments though, this will probably not do what you expect it to do.正如评论中指出的那样,这可能不会像您期望的那样。 This will do a pointer comparison and not a comparison of the actual strings.这将进行指针比较,而不是实际字符串的比较。 You'll need to use strcmp for that.为此,您需要使用strcmp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM