HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

Is this the best way to reverse a string in C (not in place)?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thisthereverseplacewaynotstringbest

Problem

Here is my code. Is there anyway to make it more efficient?

/*
IN: string to have characters reversed
OUT: string containing characters in reversed order
*/
char* reverStr(const char *str)
{
        char* revStr = (char*)malloc(strlen(str));
        int i;
        for(i = strlen(str)-1; i >= 0; i--)
            revStr[strlen(str)-1-i] = str[i];
        return revStr;
}

Solution

What about this:

/*
IN: string to have characters reversed
OUT: string containing characters in reversed order
*/
char* reverStr(const char *str)
{
        int index=strlen(str);
        char* revStr = (char*)malloc(index--);
        int destIndex=0;
        while (0<=index)
            revStr[destIndex++] = str[index--];
        revStr[destIndex]=0; 
        return revStr;
}

Code Snippets

/*
IN: string to have characters reversed
OUT: string containing characters in reversed order
*/
char* reverStr(const char *str)
{
        int index=strlen(str);
        char* revStr = (char*)malloc(index--);
        int destIndex=0;
        while (0<=index)
            revStr[destIndex++] = str[index--];
        revStr[destIndex]=0; 
        return revStr;
}

Context

StackExchange Code Review Q#32234, answer score: 5

Revisions (0)

No revisions yet.