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?