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.

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.

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
}

}
``````

Thank you all for your help!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.