Look at the following code:
#include <iostream>
#include <string>
using namespace std;
void reverseStr(string arr, int start, int end)
{
while (start < end)
{
swap(arr[start], arr[end]);
++start;
--end;
}
}
int main()
{
string str = "CPP";
reverseStr(str, 0, 3);
cout << str;
return 0;
}
The output is CPP, while PCC is expected.
Question: How to pass string by reference in C++? Are strings a normal array? If yes then the reference must be passed automatically, while it just creates a copy in the formal parameters.
My question is that why I have to use my function like void reverseStr(string &arr, int start, int end)
instead of just void reverseStr(string arr, int start, int end)
. Why I have to use extra &
informal parameters? Aren't string variables just other arrays?