指针解除引用

时间:2014-10-28 08:14:18

标签: c++

char *m_chString="asd"; 
cout<<m_chString;//prints asd
cout<<*m_chString;//prints a


int nValue = 7;
int *pnPtr = &nValue;
cout<<*pnPtr;//prints 7
cout<<pnPtr;//prints the address of nValue

我给出了两个例子,第一个指针指向一个字符串,第二个指针打印到一个int值。
我的问题是,为什么第一个示例中的cout<<m_chString;不会像第二个示例中那样打印字符串的地址,如果我打印pnPtr而不取消引用它?
不是pnPtr指向一个地址吗?

1 个答案:

答案 0 :(得分:2)

原因是std :: cout会将char *视为指向C风格字符串(的第一个字符)的指针,并将其打印出来。

您可以通过以下方式打印地址: -

    cout << (void *) m_chString;

或者如果你是伟大的C ++粉丝那么

    cout << static_cast <const void *> (m_chString);
相关问题