PuppeyD PuppeyD - 1 month ago 20
C++ Question

Printing the reference of char

What does

&c
mean in the following code?

string s("hello");
for(char &c:s){
cout<<&c<<endl;
}


I have konwn it should be
cout<<c<<endl;
if I want to print
s
.
when i added
&
before
c
it becomes


hello

ello

llo

lo

o

Answer

&c return char*. The operator << is overloaded in order to deal with char* as array of characters. It was implemented to print the whole string that the char* points to until the terminate character rather than printing the address of c.

If you want to print the address of c:

std::string s("hello");
for(char &c:s){
    std::cout<<static_cast<void*>(&c)<< '\n';
}
Comments