I am new to pointers and i cant figure out one simple thing.
int main ()
{
char *str1="pointer";
printf("%p \n", str1);
cout << str1<<endl;
return 0;
}
The output is as follows :
0000000000409001
pointer
Could someone please explain me the difference here. why isnt cout printing the memory address ? how can i make cout print the address of str1?
The format specifier %p prints a void *, (untrue: so the char * is implicitly converted to void *) the char * is converted to void * before printing. (But this is actually undefined behavior, see comments. The correct way to do that would be printf("%p", (void *) str1);) The corresponding C++ code would be std::cout << (void *) str1 << '\n';.
The code std::cout << str1; prints str1 as null terminated string. The corresponding C-code would be printf('%s', str1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With