Reputation: 19
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?
Upvotes: 0
Views: 2474
Reputation: 173044
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]
.
Upvotes: 4