Why does my pointer output a string and not a memory address in C++? [duplicate]

匆匆过客 提交于 2019-11-28 01:23:01
Mysticial

This is because the << operator has been overloaded to handle the case of a char* and print it out as a string. As opposed to the address (which is the case with other pointers).

I think it's safe to say that this is done for convenience - to make it easy to print out strings.

So if you want to print out the address, you should cast the pointer to a void*.

The variable pString is a pointer. However, the implementation of << when used with an output stream knows that if you try to output a char *, then the output should be printed as a null-terminated string.

Try:

cout << static_cast<void *>(pString);

This is down to the fact that "<<" will automatically follow the pointer and print out the string instead of just printing out the memory address. This is easier to see in printf as you can specify the print out of a pointer OR what the pointer references.

#include <stdio.h>
#include <stdlib.h>

int main(int argc,char** argv)
{
    char string1[] = "lololololol";
    char* string2;

    string2 = string1;

    printf("%s",string2);
    printf("%p",string2);

    return EXIT_SUCCESS;
}

You can see here that %s prints out the string and %p prints out the memory address.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!