问题
Many a times I have seen the following statements:
char* ch = "Hello"
cout<<ch;
The output I get is "Hello". I know that ch points to the first character of the string "Hello" and that "Hello" is a string literal and stored in read only memory. Since, ch stores the address of the first character in the string literal, so shouldn't the statement,
cout<<ch;
give the output "the address of a character" because, it is a pointer variable? Instead it prints the string literal itself.
Moreover, if I write this,
ch++;
cout<<ch;
It gives the output, "ello". And similarly, it happens with more consecutive ch++ statements too.
can anybody tell me, why does it happen?
Btw, I have seen other questions related to string literals, but all of them address the issue of "Why can't we do something like *ch='a'?
EDIT : I also want to ask this in reference to C, it happens in C too, if I type,
printf("%s",ch);
Why?
回答1:
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* );
回答2:
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.
回答3:
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.
来源:https://stackoverflow.com/questions/27632481/pointers-and-string-literals