Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between printf() and std::cout with respect to pointers

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?

like image 366
amolgautam Avatar asked Sep 12 '26 07:09

amolgautam


1 Answers

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

like image 76
n314159 Avatar answered Sep 13 '26 22:09

n314159



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!