so my i want to replace a char of a string at a given pos. so i was practicing call my reference and call by address. when i call by reference the code works but for some reason when i call by address the code does not work. from what i understand of pointers if im wrong please correct. in replace function a pointer p is created pointing to the str[0]. so if i say p[4] wouldnt that mean p is now pointing to the fourth address of str? so cant i just have that value changed and then dereference my pointer. or is the pointer only able to point to one specific address of my string?
so if input is str is apple, pos is 2, str1 is 'e', then output should be apele.
i edited my code to create another string to store the string pointed upon by p in order to display it. but ran into an error
main.cpp:8:14: error: indirection requires pointer operand
('std::string' (aka 'basic_string<char>') invalid)
str[i]=p[i];
i want to replace a char of a string at a given pos
1 2 3 4
void replace_char_at_index(std::string* ps, char ch, int index)
{
ps->at(index) = ch; // or (*ps)[index] = ch;
}
Note that ps[index], only when ps is a pointer type, is shorthand for *(ps + index)
This pointer arithmetic treats ps as the address of the first element of an array - not what you want.
p is a pointer to a string or an array of strings. *p and p[0] are the string that p points to, but p[1] and p[2] are the second and third strings in the array, not the 2nd and 3rd characters in *p.