指针和地址
问题描述:
考虑下面的例子指针和地址
int nCount[2] = {5,10};
int* ptrInt;
ptrInt = nCount;
cout<<ptrInt<<Endl;//this will print the address of arrar nCount
现在考虑这个
char *str = "Idle mind is a devil's workshop";
int nLen = strlen(str);
char* ptr;
ptr = new char[nLen+1];
strcpy(ptr,str);
cout<<ptr<<endl;//this wil print the string
,但不应该将这种打印str的地址。我没有太大的区别。
答
由于char*
s经常用于存储字符串,因此的输出流operator<<
被重载以打印出指向字符串而不是指针。
如果要输出指针,可以将指针投射到void*
,然后输出该指针。
答
如果你想地址:
cout << (void *) ptr < <endl;
的< <运算符重载大量的类型 - 对于char *,它打印的字符串,无效*它打印的地址。
答
那么,处理char*
作为特例的流操作符有一个超载。所有其他类型的指针都使用void*
重载。以下是标准流操作符的相关超载:
basic_ostream<charT,traits>& operator<<(const void* p); // all types of pointers
template<class charT, class traits> // except for c-strings
basic_ostream<charT,traits>& operator<<(basic_ostream<charT,traits>&,
const char*);
标准流可以处理其他类型的字符,但这只是我不会添加到我的答案中的一个细节。 – AraK 2010-05-01 18:24:08