Invert a character array.

Hello,

So I found this exercise in the book I'm currently reading;

Create a function that will invert (translating this on the fly - basically just switch the last element in the first element and second last to second first etc etc) a char[] string, using 2 pointers, and the functions needs to only take one pointer as a parameter.


So, here's the spaghetti code i've got so far:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <string>

void turnstring (char * pstr)
{
	char * cptr;
	char saver[6];
	cptr = pstr;
	int it = 1;
	for (int i=0; i < cptr[5]; i++, it++)
	{
		saver[i] = cptr[i-it];
	}
	std::cout << saver;
	return;
}



int main()
{
	char mystring[] = "hello";
	char * testp;
	testp = mystring;
	turnstring(testp);
	system("pause");
	return 0;
}


So I basically start with the "mystring" variable to hold my test string, which is "hello" (for testing purposes i've set all the iterators and conditions in the function to only iterate through 6 just to make it easier this far).

I send the "testp" pointer to the function, and also create a new character string inside the function, named "saver", which I had thought I could just loop through all the characters in "cptr" and then directly save them to saver through each iteration of the loop.


I'm pretty much lost at this point, any advice on how I should properly fix the for loop?
Try i < 6
err, thanks I guess.. :P

Any other advice on fixing this?
it needs to hold the index of the last char (4), you're not supposed to change both i and it (otherwise i-it will be constant), i-it should be it-i, i should not go to cptr[5] (cptr[5] is the terminating null character) but rather to 5 and you have to null-terminate saver.

Or just like this:
1
2
3
4
5
void turnstring (char* pstr)
{
	const int len=strlen(pstr);
	for (int i=0;i<len/2;i++)std::swap(pstr[i],pstr[len-i-1]);
}
Ah, that's exactly what I was looking for, it makes sense now!

Thanks :)
Topic archived. No new replies allowed.