I was given a function and told to make it reverse the characters in a character array without using any work arrays.
Here is what I had.
1 2 3 4 5 6 7 8 9 10 11 12 13
void reverse(char myWord [])
{
char* a = myWord;
a--;
char* b = myWord;
for(int i = 0; a < b; i++)
{
*a = *b;
a--;
b++;
}
return;
}
Yet when run, after input the word, it gets a runtime error and needs to close down. I dunno what the cause of this is and it's been frustrating me a lot.
On line 4, you move a to point to one byte before the start of thr string...why? Remove this line.
On line 5, you set B to the start of myWord instead of the end...you need to point it to the end, not the start.
On line 6, you declare and increment i, but don't use it...you can exclude everything except the condition from a for loop, but that is what a while loop is for.
On line 8, you need to switch the characters, not just assign one of them. EG, a goes to temp, b goes to a, and temp goes to b.
On lines 9 and 10, you decrement a instead of increment, and increment b instead of decrement (assuming you fixed line 5)