Hello,
I need to write a program that takes a string and reverses it via pointers. I have a function called Reverse and what it does is take to pointers (front and rear) and intializes them to the front and back of the char array respectively. Then what it does is one by one go through the char array and switches front with rear. Finally front++ and rear-- until they equal each other. The problem I am having is outputting new array. What am i doing wrong?

void Reverse(char entry[], int &length)
{
    int i = 0, j = length - 1;
    char *front, *rear;
    char temp;

    while (i != j)
    {
        *front = entry[i];
        *rear = entry[j];
        temp = *front;
        *front = *rear;
        *rear = temp;
        i++;
        j--;        
    }

    for (int k = 0; k < length; k++)
    {
        cout << entry[k];
    }
}

Here:

*front = entry[i];

this assigns the character at entry[i] to the memory at the address represented by front, but front hasn't been allocated any memory. I suspect what you want is to assign to the pointer the address of the character, like this:

front = &entry[i];

The same applies to the line that follows, with rear.

Watch out also for this:

 while (i != j)

because depending on whether there is an odd or even number of characters i may never equal j.

Edited 4 Years Ago by Bob

Just a note to add that if the task you've been set is to do this with pointers, you can get rid of integers i and j and does this just through three pointers front, rear and temp.

Edited 4 Years Ago by Bob

Exactly as Bob suggested, just fill in the blanks.

void Reverse(char entry[ ], int length)
{
    if (0 == length) // if (!length)
        return;

    char *front = &entry[0];
    char *rear  = &entry[length - 1];
    char temp;

    while (front < rear)
    {
        // swap front/rear 
        // increment front ptr, decrement rear ptr        
    }


}
This question has already been answered. Start a new discussion instead.