'Why does this C reverse string function not work?
I'm confused why I get an empty string when I print out reversed. Printing out the character at each iteration seems to be working ok.
Output:
original string: testing
g
n
i
t
s
e
t
reversed:
#include <stdio.h>
#include <string.h>
void reverse_string(char string[]) {
int str_len = strlen(string);
char reversed[20];
int j = 0;
for (int i = strlen(string); i>= 0; i--) {
char tmp = string[i];
reversed[j] = tmp;
printf("%c\n", reversed[j]);
j++;
}
reversed[j] = '\0';
printf("reversed: %s", reversed);
}
int main (void) {
char string[8] = "testing";
printf("original string: %s", string);
reverse_string(string);
return 0;
}
Solution 1:[1]
i starts at strlen(string), which points to the terminating '\0' character. That character is copied into position 0 in the reversed string, so any characters after that are not considered part of the string.
Solution 2:[2]
for (int i = strlen(string); i>= 0; i--) {
char tmp = string[i];
string[strlen(string)] is by definition always the string termination character '\0'. You have to start your loop at strlen(string)-1.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Thomas |
| Solution 2 | Erich Kitzmueller |
