打印指针值

1 c++ pointers

我编写了以下程序来了解向指针值添加整数值.在我的例子中,指针指向整数.我知道如果p是一个指向整数的指针,那么p + 2是存储"两个整数前面"(或2*4个字节= 8个字节)的整数的地址.下面的程序按照我对整数数组的预期工作,但对于char数组,它只打印空行.有人可以向我解释原因吗?

#include <iostream>

int main() {

    int* v = new int[10];

    std::cout << "addresses of ints:" << std::endl;

    // works as expected
    for (size_t i = 0; i < 10; i++) {
        std::cout << v+i << std::endl;
    }

    char* u = new char[10];

    std::cout << "addresses of chars:" << std::endl;

    // prints a bunch of empty lines
    for (size_t i = 0; i < 10; i++) {
        std::cout << u+i << std::endl;
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

cni*_*tar 6

这是因为它char *具有特殊意义(C字符串)所以它会尝试将其打印为字符串.投射指针让我们cout知道你想要什么:

std::cout << (void *)(u+i) << std::endl;
Run Code Online (Sandbox Code Playgroud)

  • @curvature,FFR,应该是`const char*`(或`std :: string`,因为这是C++).内容是只读的,您应该在变量的类型中反映出来. (2认同)