Search code examples
arrayscpointersswapc-strings

Why is my code not giving me correct results


I have this code that is supposed to swap between two consecutive strings in an array of strings. I am getting this output:

adf
nmmmmmmm
gh
11kk%$#
abcd

It's supposed to give me this output

adf
nmmmmmmmMMMMMM
gh
11kk%$#
abcd

This is my code:

#include <stdio.h>

void swap( char **t1,char **t2)
{
    char *t;
    t = *t1;

    *t1 = *t2;
    *t2 =t;
}

int main() {
    char array[][21]={"abcd","adf","nmmmmmmmMMMMMM","gh","11kk%$#"};
    
    for(int i=0;i<4;i++){
        swap(&array[i],&array[i+1]);
    }
    
    for(int i=0;i<5;i++){
        printf("%s\n",array[i]);
    }
    
    return 0;
}

Anyone have an idea why?


Solution

  • The function declaration and its call are incorrect.

    In this call

    swap(&array[i],&array[i+1]);
    

    the arguments have the type char ( * )[21] while the function parameters have the type char **. And there is no implicit conversion from one type to another.

    What you need is to swap strings by exchanging contents of character arrays using the standard C string function strcpy.

    The function can be declared and defined the following way

    #include <string.h>
    
    //...
    
    enum { N = 21 };
    
    void swap( char *t1, char *t2 )
    {
        char t[N];
        strcpy( t, t1 );
        strcpy( t1, t2 );
        strcpy( t2, t );
    }
    

    and the function should be called like

    swap( array[i], array[i+1]);
    

    Here is a demonstrative program.

    #include <stdio.h>
    #include <string.h>
    
    enum { N = 21 };
    
    void swap( char *t1, char *t2 )
    {
        char t[N];
        strcpy( t, t1 );
        strcpy( t1, t2 );
        strcpy( t2, t );
    }
    
    int main(void) 
    {
        char array[][N] = { "abcd", "adf", "nmmmmmmmMMMMMM", "gh", "11kk%$#" };
        
        for(int i=0;i<4;i++){
            swap( array[i], array[i+1] );
        }
        
        for(int i=0;i<5;i++){
            puts( array[i] );
        }
        
        return 0;
    }
    

    The program output is

    adf
    nmmmmmmmMMMMMM
    gh
    11kk%$#
    abcd