简体   繁体   中英

Pointers and Addresses

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.

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.

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.

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*);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM