简体   繁体   中英

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?

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

A pointer is an address to a location in memory.

"pointer" is a C-string in memory, 8 bytes for the letters and a terminating NULL byte. str1 is a pointer to the byte of the first letter 'p' .


printf("%p", str1) prints the value of the pointer itself, that is the memory address (in this case 0000000000409001 ).

printf("%s", str1) would print pointer , the content of the C-string at location str1 .


cout << str1 << endl also prints the content of the C-string. This is the default behavior for pointer of type char* because they are usually strings.

cout << static_cast<void*>(str1) << endl would print the address of the pointer again.

a char* is a pointer to the beginning of an array of characters.

cout "recognizes" a char* and treats it like a string.

You are explicitly telling printf() to print out the decimal representation of a pointer address with the %p formatter.

You are explicitly telling printf() to print out of the pointer address with the %p formatter.

EDIT: edited for accuracy based on comment

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