there is a string, I want to make a pointer to it and directly change the first element through the pointer:

#include <iostream> #include <string> using namespace std; int main() { string a = "abcdefg"; string* b = &a; cout << a << endl; b[0] = "b"; cout << a << endl; return 0; } 

but when compiling I get the answer

  abcdefg b 

if i try b[1] = "c"; then the answer will be:

 abcdefg abcdefg 
  • Well, you are already well told. I'm just wondering if you didn’t notice any inconsistencies here - trying to assign a string to a symbol (well, as you thought): b[0] = "b" . Well, directly through the pointer you can write what you wanted and, for example, like this: b->operator[](0) = 'b'; :) - Harry

1 answer 1

You are confused using the operator [] :

 string* b = &a; // ... b[0] = "b"; 

The string b[0] equivalent to *(b + 0) , which in turn is equivalent to *b . So you just rewrote the entire string a , because b points to it.

 b[1] = "c"; 

But this is absolutely impossible to do. You are trying to access memory at an address that you may not belong to, which leads to undefined behavior.

In order to change a specific character in a string through a pointer to it, you must first dereference the pointer, and only after that change the element itself:

 (*b)[1] = 'с'; 

Example:

 #include <iostream> #include <string> int main() { std::string a = "abcdef"; std::string* b = &a; std::cout << a << std::endl; (*b)[1] = 'c'; std::cout << a << std::endl; }