Archive for April, 2011

Reversing A String With C

The most common interview question I hear about is the problem involving reversing a string. There are countless methods to do so, many of which are so creative it makes you wonder how anyone came up with a solution. One aspect of the problem I’ve never heard discussed concerns the method used to declare the string. The answer can vary depending on if the string the function is reversing is a char* or a char array[]. Char arrays can be manipulated character by character whereas strings, char* in this case, are immutable.

Let’s begin with a solution that always works, regardless how the string is declared.

The function below, reverse1, takes a char* as input and returns a new pointer to a block of memory it will allocate with malloc. The function simply “reverse copies” the input string into the new string.

char* reverse1(char* myStr)
{
    int i, len;
    len = strlen(myStr);
    char* newStr = (char*)malloc((len+1)*sizeof(char));
    
    for (i=0; i<len; ++i)
    {
        newStr[len-1-i] = myStr[i];
    }
    newStr[len] = ‘\0’;

    return newStr;
}

The wonderful aspect of the above code is it will work on both char* strings and arrays of chars. All of the following strings can be passed as input:

// Arrays
char str1[] = “Hello”;
char str2[6] = “Hello”;
char str3[10];
printf(“Enter string> ”);
scanf(“%s”, str3);
char str4[] = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘’};

// strings
char* str5 = “Hello”;

However, one may want to perform the same reverse task without allocating new memory, or may infact wish to reverse the block of memory passed into the funtion instead of receiving back a pointer to a new block of memory. Here is another solution that accomplishes this.

If one attempts to pass in all the strings declared above, they will run into a problem.     This function attempts to get down and dirty with the string and rearrange the elements swapping the first element with the last and so on. The application will crash when passing in a pointer to a string (char*). Strings are immutable while arrays can be manipulated.

void reverse2(char* myStr)
{
    int i, len;
    char temp;
    len = strlen(myStr);
   
    for (i=0; i<len/2; ++i)
    {
        temp = myStr[i];
        myStr[i] = myStr[len-1-i];
        myStr[len-1-i] = temp;
    }
    myStr[len] = ‘’;
    return;
}

Leave a Comment