Pointers and String Literals
I have seen the following statements many times:
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 is stored in read-only memory. Since ch stores the address of the first character in a string literal, so there shouldn't be an instruction,
cout<<ch;
give the output " character address " because it is a pointer variable? Instead, it prints the actual string literal. Moreover, if I write this,
ch++;
cout<<ch;
It prints the output of " ello ". And similarly, this happens with more sequential ch ++ instructions.
can someone tell me why this is happening?
BTW, I've seen other questions related to string literals, but they all touch on the issue "Why can't we do something like: ch =" a "?
EDIT: I also want to ask this with a reference to C, this happens and in C if I type
printf("%s",ch);
Why?
source to share
Overloaded version operator<<
ostream& operator<< (ostream& , const char* );
This overload is called whenever you use something like: -
char *p = "Hello";
cout << p;
This overload determines how to print this line, rather than print the address. However, if you want to print the address, you can use
cout << (void*) p;
as this will trigger another overload that just prints the address to the stream: -
ostream& operator<< (ostream& , void* );
source to share
Printing char * in C ++ gives you a string, not a pointer, because that's how the language is defined, and in turn because it makes sense and is useful. After all, we rarely need to type the address of a string. In terms of implementation, this can be achieved by operator overloading:
std::ostream& operator <<(std::ostream&, const char*);
You can find something like this 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 is ch++
giving you a string starting at the second character, well, what, since incrementing a pointer advances it to the next item in the "array" it points to.
source to share
To answer your edited question regarding printf()
to c
, it is defined 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
, it is %s
used to print a string, whereas it is %p
used to print the pointer itself p
.
source to share