I am trying to create a program that reverses a string with pointers and functions in C++, but so far, my method is only returning an empty string rather than a reversed one.
#include <iostream>
using namespace std;
void invertS(string *str_ptr );
int main()
{
string value {"Hello"};
string *str_ptr {nullptr};
str_ptr = &value;
invertS(str_ptr);
cout << value;
};
void invertS(string *str_ptr) {
string str = *str_ptr;
string temp = "";
int length = str.length();
int j = length - 1;
for (int i = 0; i < length; i++) {
temp[i] = str[j];
j--;
};
*str_ptr = temp;
};
The result is always just an empty string. Note that I'm assigning the string referenced by str_ptr to a new string inside the function so that I can use .length on the string. Since .length cannot be used on a pointer as far as I know. If there's a better way to do that, I'd also appreciate to know how it goes.