2

For example, i have the following string :

std::string s = "Hello, World!"

I want the address of the last element of s which is '!'.

I tried the following code, but it does not seem to output what I want it to.

std::cout << &s[s.length() - 1];

That outputs '!' not it's address, the same happens with s.back()

Is it because of the formatting caused by std::cout or is the problem elsewhere?

Basically I want a function that outputs the address of the last (and if possible, the first) element in a string.

Investor
  • 185
  • 7

2 Answers2

9

Currently, you're using the overload of operator<< that takes a const char* as input. It treats the input as a null-terminated C string.

If you cast to (const void*) the problem will go away:

std::cout << (const void*)(&s[s.length() - 1]);
Remy Lebeau
  • 505,946
  • 29
  • 409
  • 696
Bathsheba
  • 227,678
  • 33
  • 352
  • 470
1
auto address_back = &s.back();
auto address_front = &s.front();

cout << static_cast<void*>(address_back) << endl;
cout << static_cast<void*>(address_front) << endl;
Curious
  • 20,072
  • 7
  • 51
  • 128