0

I'm trying to make a function which performs some operations on strings. From my understanding, strings are character arrays. So by writing:

cout << name[0];

we print the first character written of an assumed string called 'name'.

In my function, I have to use pointers to perform all functions. My current approach is to make a pointer:

string *str=&name;

but when I try to print the character at specified index by writing:

cout << *str[0];

It doesn't compile, I'm not sure what is the problem. One solution would be to make a dynamic character array but I wanted to know if it is possible to get the character at certain indexes of strings using pointers?

7
  • "print an index" not sure i understand what exactly do you mean (given your example). Commented May 10, 2018 at 14:26
  • Use iterators not pointers Commented May 10, 2018 at 14:26
  • @Raxvan Say string name="abcd"; cout << name[0]; prints 'a'. How to do the same but using pointers? Commented May 10, 2018 at 14:28
  • @Raxvan It seems OP wants print the char at specified index. Commented May 10, 2018 at 14:32
  • @songyuanyao ah , i see now Commented May 10, 2018 at 14:34

1 Answer 1

4

operator[] has higher precedence than operator*, so *str[0] is same as *(str[0]). str[0] returns a std::string, and calling operator* on std::string doesn't make sense.

Change it to (*str)[0].

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.