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

我与影子孤独终老i 提交于 2019-11-28 05:18:21

问题


This question already has an answer here:

  • cout << with char* argument prints string, not pointer value 6 answers

I'm working on a string class that employs pointers and I'm just having some difficulty in understanding how my print function works here. Specifically, why does cout << pString output the string and not the memory address of the dynamic array that it's pointing to? My understanding was that the variable pString was a pointer.

class MyString
{
    public:
        MyString(const char *inString);
        void print();
    private:
        char *pString;
};


MyString::MyString(const char *inString)
{
    pString = new char[strlen(inString) + 1];
    strcpy(pString, inString);
}

void MyString::print()
{
    cout << pString;
}

int main( )
{
    MyString stringy = MyString("hello");
    stringy.print();
    return 0;
}

回答1:


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*.




回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/7788639/why-does-my-pointer-output-a-string-and-not-a-memory-address-in-c

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