Search code examples
cfor-loopcharmallocc-strings

String allocated with malloc is only returning the first character


I'm writing a function to rearrange a string's characters. I allocated the new string with malloc and initialize it, and then return it. But when I return it, it always only returns the first character.

I've tried printing the characters of the new string one by one and they print out correctly, but when I call the function, only the first character is returned. I can't figure out why. Any help would be appreciated! Here's my code:

char * solution(char * s) {
    int len = strlen(s);
    int i;
    int index = 0;
    
    char *ans = (char *) malloc(sizeof(char) * (len + 1));
    if (ans == NULL) {
        fprintf(stderr, "Ran out of space in some function \n");
        exit(1);
    }
    //char* ans = (char *) malloc(len + 1);
    ans[len] = '\0';
    
    for(i = 0; i < len/2; i++){
        ans[index++] = s[i];
        
        ans[index++] = s[len - i];
    }
    if(len % 2 == 1){
        ans[index] = s[len/2];
    }
    return ans;
}


Solution

  • In the first iteration of this for loop

    for(i = 0; i < len/2; i++){
        ans[index++] = s[i];
        
        ans[index++] = s[len - i];
    }
    

    the character ans[1] is set to s[len] (i is equal to 0 in the first iteration of the loop) that is to '\0'.

    As a result you will get a string that contains only one character.

    What you do is what you get.:)

    It seems you mean

    ans[index++] = s[len - i - 1];
    

    Pay attention to that as the source string is not changed within the function then the function should be declared like

    char * solution( const char * s );
    

    The original declaration

    char * solution(char * s);
    

    means that the string will be changed in place.

    If you want to change a string in place then the function can look the following way as shown in the demonstration program below.

    #include <string.h>
    #include <stdio.h>
    
    char * solution( char *s )
    {
        size_t n = strlen( s );
    
        for (size_t i = 1; i < n; i += 2)
        {
            char c = s[n - 1];
            memmove( s + i + 1, s + i, n - i - 1);
            s[i] = c;
        }
    
        return s;
    }
    
    int main( void )
    {
        char s[] = "0123456789";
        puts( s );
        puts( solution( s ) );
    }
    

    The program output is

    0123456789
    0918273645