Home > Software design >  How do I return a reversed string of characters?
How do I return a reversed string of characters?

Time:12-13

I tried to reverse a string of characters in C programming language. I was given a string in my main function which serves as argument for reverse_string function when it is called such that I will return the reverse of the given string. I am not permitted to use printf as output .... It must return the reversed string

See my code below for reference

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *reverse_string(char *param_1)
{
    int i;
    int n = strlen(param_1);
    char *reverse, temp;

    for (i = n - 1; i >= 0; i--)
    {
        // printf("%c", param_1[i]);
        // printf("%c", param_1[i]);
        temp = param_1[i];
        // printf("%c", temp);
        reverse = &temp;
        printf("%c", *reverse);
    }
    return reverse;
}

int main()
{
    char *str = "games";
    reverse_string(str);
    return 0;
}

CodePudding user response:

there is One way you can allocate the string on the heap

char *mystring = malloc(strlen(param_1) 1);

and then free the memory in your main function

CodePudding user response:

Use malloc() to allocate a result string that's large enough to hold a copy of the parameter.

Then copy the characters from the parameter string to the result string in reverse.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *reverse_string(char *param_1)
{
    int i;
    int n = strlen(param_1);
    char *reverse = malloc(n 1);
    reverse[n] = '\0'; // Add null terminator

    for (i = 0; i < n; i  )
    {
        reverse[n-i-1] = param_1[i];
    }
    return reverse;
}

int main()
{
    char *str = "games";
    char * reversed = reverse_string(str);
    printf("%s\n", reversed);
    free(reversed);
    return 0;
}

CodePudding user response:

Promoting my solution to pass the string into the function as arguments instead, it would be like:

#include <stdio.h>
#include <string.h>

char *reverse_string(const char *original, char *reverse, size_t reverse_size)
{
    const char *original_start = original;
    const char *original_end = original   strlen(original) - 1;

    char *reverse_start = reverse;
    char *reverse_end = reverse   reverse_size - 1;

    for (/* empty */;
         original_end >= original_start &&
         reverse_start < reverse_end;
         --original_end,   reverse_start)
    {
        *reverse_start = *original_end;
    }

    // Terminate the reverse string
    *reverse_start = '\0';

    // And return it
    return reverse;
}

int main(void)
{
    const char *original = "Hello world!";
    char reverse[strlen(original)   1];

    printf("Reverse of \"%s\" is \"%s\"\n", original,
           reverse_string(original, reverse, sizeof reverse));
}

Also note that I use a different technique to reverse the string, by using pointers. The parameter passing would work just as well with your technique of using indexes.

  • Related