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;
}
CodePudding user response:
char *result = new char[len 1];
This line allocates a new string (length of the other string's characters, plus one for the terminating null), and stores it in result. Note that result points to the beginning of the string, and is not modified.
char *res = result len;
This line is making res point to the end of result: res is a pointer that equals the address of result, but len characters after.
*res-- = '\0';
This line:
- writes a terminating NULL to
res, which currently points to the end ofresult, and - decrements
resso that it now points to the previous character of result
while (*str)
*res-- = *str ; // swapping character?
These lines:
- loop until
strpoints to a NULL - write the character pointed to by
strto the destination memory pointed to byres, and res--: decrementresto point to the previous location in memory, andstr: incrementstrto point to the next character ofstr
return result; // why not res?
Result is returned because it points to the (beginning of) the new string.
