tags:

views:

63

answers:

3

Consider the below example

int nCount[2] = {5,10};
int* ptrInt;
ptrInt = nCount;
cout<<ptrInt<<Endl;//this will print the address of arrar nCount

now consider this

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 

but shouldnt this be printing the address of str. I am not quite getting the difference.

+7  A: 

Since char*s are frequently used for storing strings, the ostream operator<< is overloaded for char* to print out the pointed-to string instead of the pointer.

If you want to output the pointer, you can cast the pointer to void* and then output that.

James McNellis
+1  A: 

If you want the address:

 cout << (void *) ptr < <endl;

The << operator is overloaded for lots of types - for char *, it prints a string, for void * it prints the address.

anon
+1  A: 

Well, there is an overloading for the stream operator that deals with char* as a special case. All other types of pointers are using the void* overloading. Here are the relevant overloading of the stream operator from the standards:

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
Standard streams can deal with other types of characters but that's just a detail I wouldn't add to my answer.
AraK