【问题标题】:confusion of char* str="ab", str and &strchar* str="ab"、str 和 &str 的混淆
【发布时间】:2015-10-06 15:24:17
【问题描述】:

我正在学习指针,这是我的代码。我定义了一个指向 char(实际上是字符串)*str 的指针和一个指向 int *a 的指针,它们的定义方式相同。我以为stra都应该是一个地址,但是当我尝试输出str&straa&a时,我发现str不是地址,它是字符串。 char *str 和 int *astra 的类型上有什么区别?谢谢你。

#include<iostream>
#include<string>
using namespace std;
int main()
{
        char *str = "FA";
        cout << "str: " << str << endl;
        cout << "&str: " << &str << endl;

        int b = 5;
        int *a = &b;
        cout << "a: " << a << endl;
        cout << "&a: " << &a << endl;
}

这是输出:

str: FA
&str: 0x7fff5a627280
a: 0x7fff5a62727c
&a: 0x7fff5a627288

【问题讨论】:

  • 优先使用const char * 作为字符串字面量。

标签: c++ c string pointers


【解决方案1】:

嗯,这归结为 C 语义。字符串不是 C 中定义的类型。char单个 字符的类型。为了在 C 中处理字符串,按照约定,指向 char 的指针表示从该指针指向的位置开始并在第一个 0 字节处结束的字符串。

为了清楚说明:

char *str = "ABC";

“翻译”成类似的东西

const char <nosymbol>[4] = {'A', 'B', 'C', '\0'};
char *str = &(<nosymbol>[0]);

C++ 知道 char * 的这种特殊含义,因此,&lt;&lt; 运算符将遵循 C 程序员的最小意外原则,将 char * 作为字符串。

【讨论】:

    【解决方案2】:

    流的&lt;&lt; 运算符对char * 有一个重载,它输出一个C 风格的字符串。这通常是您想要的,但如果不是您想要的,您可以使用reinterpret_cast&lt;void*&gt;addressof

    【讨论】:

    • 一个更有表现力的解决方案是cout &lt;&lt; addressof(str)
    • addressof(str) 是第二个输出行的详细替代方案,这没有问题。称其为“更具表现力”是愚蠢的。
    猜你喜欢
    • 1970-01-01
    • 2022-10-12
    • 2011-04-21
    • 2022-06-15
    • 2011-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多