C++字符数组不显示地址

标签 c++

<分区>

我正在试验 char 数组,然后尝试运行这个程序:

#include <iostream>

using namespace std ;

int main ( )
{
    char *str = "Hello!" ;

    cout << &str[0] << endl ;
    cout << &str[1] << endl ;
    cout << &str[2] << endl ;
    cout << &str[3] << endl ;
    cout << &str[4] << endl ;

    return 0 ;
}

我不断得到这些输出:

Hello!
ello!
llo!
lo!
o!

这里究竟发生了什么?我期待的是十六进制值。

最佳答案

当你获取数组元素的地址时,你会得到一个指向数组的指针。

c++ 中,与 c 一样,字符数组(或指向字符的指针)被解释为字符串,因此字符被打印为字符串。

如果你想要地址,只需将一个强制转换添加到 (void *)

#include <iostream>

using namespace std ;

int main ( )
{
    const char *str = "Hello!" ;

    cout << (void*) &str[0] << endl ;
    cout << (void*) &str[1] << endl ;
    cout << (void*) &str[2] << endl ;
    cout << (void*) &str[3] << endl ;
    cout << (void*) &str[4] << endl ;

    return 0 ;
}

关于C++字符数组不显示地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24664201/

相关文章:

c++ - 如何在 C++ 中对一个数组进行排序并获得相应的第二个数组?

Android NDK 错误 :

c++ - 在 Linux 上使用 QTCreator IDE 的文件 IO

链接文件以构建 EXE 时出现 C++ 错误

c++ - Boost.Asio strand.dispatch() 可以阻塞吗?

c++ - Mingw32-Make&cmake 3.0

c++ - 在某些 C++ 编译器上使用 restrict 限定符的编译器错误

c++ - OpenCL 在 GPU 上分配结构导致垃圾

c++ - 如何在基于派生类的大小的基构造函数中分配数组?

c++ - 如何保护进程不被杀死?