Nov 12, 2016 at 5:30pm Nov 12, 2016 at 5:30pm UTC
I am trying to reverse a string using pointers and no library functions. I see a couple of videos, but they seem to favor C, not C++. My code fix has to be something simple, anyone have a direction for me to go? I don't want my code fixed and re-posted please.
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 29 30 31 32 33 34 35 36 37 38 39
//Try to reverse a string without library functions
#include <iostream>
#include <cstring>
char * revStr(char * ptrToString)
{
if (ptrToString == NULL)
return NULL;
char * ptrToBegin = ptrToString;
int length = 0;
for (;*ptrToBegin != '\0' ; ptrToBegin++)
length +=1;
char * ptrToEnd = ptrToBegin + (length-1);
while (ptrToBegin < ptrToEnd)
{
char temp = *ptrToBegin;
*ptrToBegin = *ptrToEnd;
*ptrToEnd = temp;
ptrToBegin++;
ptrToEnd--;
}
return ptrToString;
}
int main()
{
char myStr[20] = "eduD olleH" ;
std::cout << myStr << std::endl;
std::cout << revStr(myStr);
return 0;
}
Output:
eduD olleH
eduD olleH
Last edited on Nov 12, 2016 at 5:33pm Nov 12, 2016 at 5:33pm UTC
Nov 12, 2016 at 5:50pm Nov 12, 2016 at 5:50pm UTC
In the loop on line 16-17 you're incrementing ptrToBegin so that it no longer points to the beginning of the string.
Last edited on Nov 12, 2016 at 5:50pm Nov 12, 2016 at 5:50pm UTC
Nov 13, 2016 at 9:13am Nov 13, 2016 at 9:13am UTC
Step through the string checking for '\0' using ptrToEnd instead. Then the variable length isn't needed at all.
Yup, that works like a beast, thanks Chervil!
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 29 30 31 32 33 34 35
//Try to reverse a string without library functions
#include <iostream>
#include <cstring>
char * revStr(char * ptrToString)
{
if (ptrToString == NULL)
return NULL;
char * ptrToBegin = ptrToString;
char * ptrToEnd = ptrToBegin;
for (;*ptrToEnd != '\0' ; ++ptrToEnd);
ptrToEnd -=1;
while (ptrToBegin < ptrToEnd)
{
char temp = *ptrToBegin;
*ptrToBegin = *ptrToEnd;
*ptrToEnd = temp;
ptrToBegin++;
ptrToEnd--;
}
return ptrToString;
}
int main()
{
char myStr[20] = "eduD olleH" ;
std::cout << myStr << std::endl;
std::cout << revStr(myStr);
return 0;
}
I had to decrement ptrToEnd to get it to output, but now it is starting to feel like something I could put my handle on. Thanks.
Last edited on Nov 13, 2016 at 9:17am Nov 13, 2016 at 9:17am UTC