0

i am comparing string pointer with other pointer but string pointer gives error while writing this code

i tried printing element using string pointer but actually gets error


int main()
{
   string s="abcde";
   string *sh=&s;
   cout<<sh[2]<<" "<<s[2]<<endl;
}


RESULT -ERROR





4
  • Please update your question to provide a minimal reproducible example. The code in your question will not compile because it doesn't #include any headers, so string and cout are undefined. I can guess that string is std::string, but it's not clear. Also, you didn't show us the error message. I'll add a "c++" (always include a tag specifying the language you're using). Finally, "CPP" refers to the C Preprocessor; the language is "C++". Commented Nov 3, 2022 at 16:33
  • Oh, and your title refers to comparing string pointers, but there are no comparisons in your code. Commented Nov 3, 2022 at 16:34
  • What's the benefit of comparing pointers? What are you trying to achieve? Commented Nov 3, 2022 at 17:00
  • Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Commented Nov 4, 2022 at 4:34

1 Answer 1

2

The sh variable in your code is a pointer of strings, not chars as the string content. It does not mean the same thing as s[2] because s is a string the [] operator will access its third element. When you access sh[2] you are accessing the third string address from the start of the "array of strings" represented by sh as a pointer. As you don't have this kind of data this access is invalid.

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.