c++ - Reverse char string with pointers -
i need reverse char string pointers. how can this? code:
// cannot modified !!! char s[10] = "abcde"; char *ps; // code ps = new char; int count = 5; (int = 0; < 10; i++) { if (s[i] != '\0') // not null { ps[count - 1] = s[i]; count--; } } cout << "reversed = " << ps;
sometimes if works fine, see 5 chars, reversed. see chars (looks temp symbols). miss something? thank you!
your char array "s" contains 10 chars, initialize first 6 chars of array "abcde" , \0 terminator. when loop on complete array, access not initialized chars.
i see, try write memory, didn't allocate. allocate memory 1 char "ps" pointer, try access it's memory array of chars in for-loop.
instead of using hardcoded:
int count = 5;
you use string function strlen() determine length of c-string.
edited (untested code):
char s[10] = "abcde"; char ps[10]; (int = 0; < strlen(s); i++) { if (s[i] == '\0') // not null { // stop loop, reach end of original string break; } ps[strlen(s) - 1 - i]; } // add termination char \0 ps array ps[strlen(s)] = '\0'; cout << "reversed = " << ps;