Home > Software engineering >  Reverse string using pointer arithmetic
Reverse string using pointer arithmetic

Time:10-11

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 of result, and
  • decrements res so that it now points to the previous character of result

    while (*str)
        *res-- = *str  ;  // swapping character?

These lines:

  • loop until str points to a NULL
  • write the character pointed to by str to the destination memory pointed to by res, and
  • res--: decrement res to point to the previous location in memory, and
  • str : increment str to point to the next character of str

    return result;  // why not res?

Result is returned because it points to the (beginning of) the new string.

  • Related