Knowee
Questions
Features
Study Tools

Write a C function, which reverses a given string and returns a pointer to reversed string.char *reverse(char *str);

Question

Write a C function, which reverses a given string and returns a pointer to reversed string.char *reverse(char *str);

🧐 Not the exact question you are looking for?Go ask a question

Solution

Sure, here is a simple implementation of a C function that reverses a given string and returns a pointer to the reversed string:

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

char *reverse(char *str) {
    int len = strlen(str);
    char *rev = malloc(len + 1);

    for(int i = 0; i < len; i++) {
        rev[i] = str[len - 1 - i];
    }

    rev[len] = '\0';
    return rev;
}

This function works by first determining the length of the input string str with strlen(). It then allocates memory for the reversed string rev with malloc(). The size of the allocated memory is len + 1 to account for the null terminator at the end of the string.

The function then enters a loop that iterates over the characters in str in reverse order. For each character, it assigns the corresponding character in rev.

Finally, the function adds a null terminator at the end of rev and returns it.

This problem has been solved

Similar Questions

Write a C program to find reverse of a string using pointers

Write a program in C to print a string in reverse using a character pointer.Also print the uppercase of the first letter of the reversed word.

Reversing a string in C is a fundamental operation that involves rearranging the characters in a string so that the last character becomes the first, the second-to-last character becomes the second, and so on.

Write c function to reverse words in sentence (without using external arrays)

algorithm for a program to reverse a number in c programming

1/3

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.