pointers and string literals

隐身守侯 提交于 2019-12-01 21:24:26

There's overloaded version of operator<<

ostream& operator<< (ostream& , const char* );

This overload is called whenever you use something like:-

char *p = "Hello";
cout << p;

This overload defines how to print that string rather than print the address. However, if you want to print the address, you can use,

cout << (void*) p;

as this would call another overload which just prints the address to stream:-

ostream& operator<< (ostream& , void* );

Printing a char* in C++ gives you the string rather than a pointer because that's how the language is defined, and in turn because that's what makes sense and is useful. We rarely need to print the address of a string, after all. In terms of implementation, it can be achieved by overloading an operator:

std::ostream& operator <<(std::ostream&, const char*);

You may find something like that in your standard library implementation, but it will actually be a template:

template <typename CharT>
std::basic_ostream<CharT>& operator <<(std::basic_ostream<CharT>&, const CharT*);

And it will probably have even more template parameters.

As for why ch++ gives you a string starting from the second character, well, that's because incrementing a pointer advances it to the next element in the "array" it points to.

To answer your edited question, regarding printf() in c, it is determined by the format specifier supplied with printf(). Check the following code

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

int main()
{

    char * p = "Merry Christmas";

    printf("[This prints the string] >> %s\n", p);
    printf("[This prints the pointer] >> %p\n", p);

    return 0;
}

Output:

[sourav@broadsword temp]$ ./a.out 
[This prints the string] >> Merry Christmas
[This prints the pointer] >> 0x80484a0
[sourav@broadsword temp]$

for the same variable p, %s is used to print the string, whereas %p is used to print the p pointer itself.

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