6

当我对正在测试的这段代码感到困惑时,我只是在玩指针和数组。

#include <iostream>
using namespace std;

int main(void) {
    char a[] = "hello";
    cout << &a[0] << endl;
    char b[] = {'h', 'e', 'l', 'l', 'o', '\0'};
    cout << &b[0] << endl;
    int c[] = {1, 2, 3};
    cout << &c[0] << endl;
    return 0;
}

我预计这将打印三个地址(a[0]、b[0] 和 c[0] 的地址)。但结果是:

hello
hello
0x7fff1f4ce780

为什么对于 char 的前两种情况,'&' 给出了整个字符串,或者我在这里遗漏了什么?

4

1 回答 1

10

因为如果您将cout'作为参数operator <<传递给它,它会打印一个字符串char*,这就是&a[0]它。如果要打印地址,则必须将其显式转换为void*

cout << static_cast<void*>(&a[0]) << endl;

要不就

cout << static_cast<void*>(a) << endl;
于 2013-06-12T17:04:47.733 回答