1

I'm trying to make sense of the following output of the string.at() function.

#include <iostream>
#include <string>

int main() {
    std::string name = "abc";
    std::cout << name.at(0) << '\n';
    std::cout << &name.at(0) << '\n';
    return 0;
}

This will output:

a
abc

I am confused as why &name.at(0) will not return the address of the first char of the string, i.e. a. Instead, it returns the complete string.

According to the doc, string::at "returns a reference to the character at position pos in the string."

yuqli
  • 4,461
  • 8
  • 26
  • 46
  • 7
    `&name.at(0)` does return `char*` which is the address of character `a`. Then that `char*` gets interpreted by `operator<<` as a pointer to a NUL-terminated string (which it is), and printed accordingly. If you want to print the address itself, cast to `void*` – Igor Tandetnik Sep 03 '18 at 17:50
  • 2
    Cast to `void*` to see the address: `(void*)&name.at(0)` – πάντα ῥεῖ Sep 03 '18 at 17:50
  • @M.M: The one in the "linked" sidebar? Actually this is a duplicate of that one. Both ask why inserting a `char*` to an output stream prints the string instead of the address stored in the pointer. – Ben Voigt Sep 03 '18 at 22:45
  • @BenVoigt the other question involves `char *` and `char **`, whereas this involves `char` and `char *`. Maybe I was too hasty though, the underlying issue is the same as you say – M.M Sep 03 '18 at 22:56

0 Answers0