Home > OS >  Why does this C reverse string function not work?
Why does this C reverse string function not work?

Time:03-05

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;
}

CodePudding user response:

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.

CodePudding user response:

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.

  •  Tags:  
  • c
  • Related