I am trying to understand how the below function *reverseString(const char *str) reverses the string with pointer arithmetic. I have been Googling and watched videos which handle similar cases but unfortunately they didn't help me out. Could you please somebody help me what may be missing for me to understand how this function works? I am using Windows 10 Pro (64 bit) with Visual Studio Community 2019. Thank you in advance for your help as always. I appreciate it.
#include <iostream>
#include <cstring>
using namespace std;
char *reverseString(const char *str)
{
int len = strlen(str); // length = 10
char *result = new char[len + 1]; // dynamically allocate memory for char[len + 1] = 11
char *res = result + len; // length of res = 11 + 10 = 21?
*res-- = '\0'; // subtracting ending null character from *res ?
while (*str)
*res-- = *str++; // swapping character?
return result; // why not res?
}
int main()
{
const char* str = "Constantin";
cout << reverseString(str) << endl;
}