2014-07-09 60 views
0

C++字符数组我用字符数组试验,然后我试图运行此程序:没有显示地址

#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! 

正是这里发生了什么?我期待着十六进制值。

+2

'字符*海峡= “你好”;'是C++ 11非法和之前弃用。 – chris

回答

5

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

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 ; 
} 
+0

是的,'&str [0]'是'char *'类型的,所以就cout而言这是一个C字符串。 – tadman

+0

是的。这工作! –

3

A char *被假定为C风格的字符串。您需要投射到void *以获取指针值。

(而你错过了const - 字符串文字是不可变的。)