2

How can I access individual elements in a std::string with pointers? Is it possible without type casting to a const char *?

#include <iostream> #include <string> using namespace std; int main() { // I'm trying to do this... string str = "This is a string"; cout << str[2] << endl; // ...but by doing this instead string *p_str = &str; cout << /* access 3rd element of str with p_str */ << endl; return 0; } 
2
  • So you want to access the third element of a string through a pointer? Commented Jul 5, 2019 at 11:17
  • It's pretty much the same as accessing any other class object by a pointer. All standard ways apply. Commented Jul 5, 2019 at 11:20

1 Answer 1

7

There are two ways:

  1. Call the operator[] function explicitly:

    std::cout << p_str->operator[](2) << '\n'; 

    Or use the at function

    std::cout << p_str->at(2) << '\n'; 

    Both of these are almost equivalent.

  2. Or dereference the pointer to get the object, and use normal indexing:

    std::cout << (*p_str)[2] << '\n'; 

Either way, you need to dereference the pointer. Through the "arrow" operator -> or with the direct dereference operator * doesn't matter.

Sign up to request clarification or add additional context in comments.

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.