why int * or void * is used in cout or in initisation @tarunluthra
After 30:00 minutes in webinar
@Nikhil-Aggarwal-2320066674901389
cout is defined in C++ in such a way that when it gets an a pointer to character , it prints not the address but the data at the location i.e. for all other pointer types , cout simply prints the address. However character pointers are an exception case. If you provide a character address to cout , it does not print the address but rather the data stored at that particular address.
In case we wish to print the address for some reason , there are two ways.
- Go old school and use printf statement of C (The older version of C++) since this modification is only for cout << , hence printf will work normally.
- If you intend to use cout<< only , then we have to fool the compiler. If we typecast the address to int* or void* and then provide it to cout statement , it will read it as character pointer but as an int pointer or a void pointer and print its address.
char ch = ‘A’ ;
cout << (void*)&ch ; // prints address
cout << &ch ; // prints data