'Reversing a string on C language

In this program, the user is allowed to enter words of up to 20 letters, which are stored in another array and printed from the end. But there is error on my code, the program output single letter after I enter a word. That is my code.

#include <stdio.h>

int main(void) {
    char user[21]; // created an array and let users enter letters
    char reverse[21]; // create an array and store the reversing string
    printf("Please enter the word that you want to reverse: \n");
    scanf("%20s", user);
    int length = sizeof(user) / sizeof(user[0]);
    int rever_index = 0;

    for (int i = 0; i < length; i++) {
        reverse[i] = user[length - i];
        rever_index++;
    }
      
    printf("reverse value are %s\n", reverse);
    return 0;
 }

Test result: Please enter the word that you want to reverse

string

reverse value are Z. How to modify my code?



Solution 1:[1]

  1. For the length of the char array use strlen(user), because you already specify how many bytes the array gonna be (user[21]), and the compiler always is taking 21 bytes no matter how many chars you input. Also don't forget to #include <string.h> for strlen.
  2. In the for loop you need to use user[length-1-i], because indexes of array are from 0 to length-1. And when you try to access user[length], it's out of bounds.

(I tried to add this explanation in the comments up but I don't have enough reputation)

#include <stdio.h>
#include <string.h>
  
int main(void) {
    char user[21]; // created an array and let users enter letters
    char reverse[21]; // create an array and store the reverseing string
    printf("Please enter the word that you want to reverse: \n");
    scanf("%20s", user);
    int length = strlen(user);
    int rever_index = 0;

    for (int i = 0; i < length; i++) {
        reverse[i] = user[length-1-i];
        rever_index++;
    }

    reverse[length] = '\0';
    printf("reverse value are %s\n", reverse);
    return 0;
}

Solution 2:[2]

There be dupes. But, just for fun, here's a bit of one liner.

/**
* Reverses a string
* @param str is the string to reverse.
* @returns a pointer to the resulting string
*/
char *rev(const char *str) {
    // get length of string
    size_t len = strlen(str);

    // allocate a string of the appropriate size
    char* r = calloc(len + 1);

    // work back down the string
    const char *s = str;
    for (; *s; ++s) 
        r[len - (s - str) - 1] = *s;

    return r;
}

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 Chris
Solution 2 Chris