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.

0

2 Answers 2

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]);
Sign up to request clarification or add additional context in comments.

3 Comments

My only complaint is that you use a C-style cast.. A static_cast should be preferred IMO. :)
@Someprogrammerdude: I see your point, but I feel that's at the expense of readability at the call site. Perhaps I spent too much time in my youth programming in C ;-)
You're still in your youth!
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;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.