c program for sort and remove duplicate values from an array

Home Forums C Programming c program for sort and remove duplicate values from an array

This topic contains 1 reply, has 2 voices, and was last updated by  GWILouisaxwzkla 8 years, 4 months ago.

  • Author
    Posts
  • #2217

    AlfredoODonnell
    Participant

    Hi ,

    I have a string array having a bunch of values. I need to sort this array, remove duplicate values from this array and reset the filtered array (without duplicate values) to a new array.

    I am new to C programming. I have written some code, but it fails with a core dump always. Can some one please correct my code or send me an easy way to do this.

    Thanks.

    code snippet:
    #include
    #include
    #include
    #include

    main ()
    {
    int stat = 0;
    int ctr = 4;
    int inx = 0;
    int status = 0;
    int j = 0;
    int k = 0;
    int reset_count = 0;
    char **lov_reset_values = 0;
    char *str[] = { “test”, “test1”, “test2”, “test” };

    for ( inx = 0; inx < ctr; inx ++ )
    {
    printf ( “str[%d] = %sn”, inx, str[inx] );
    }

    for(j=0;j
    {
    status = 0;
    for(k=1;k< =ctr;k++)
    {
    printf ( “entered after k= 0n” );
    if( strcmp (str[j],str[k] ) == 0 )
    {
    printf ( “matchedn” );
    status = 1;
    break;
    }
    }
    if ( status == 0 )
    {
    if (reset_count == 0 )
    {
    printf ( “reset_count = 0n” );
    lov_reset_values = (char **)malloc( sizeof(char *));
    }
    else
    {
    printf ( “reset_count = %dn”, reset_count );
    lov_reset_values = (char **)realloc( lov_reset_values, sizeof(char *)*(reset_count+1) );
    }

    lov_reset_values[reset_count] = (char *)malloc( sizeof( char )*(strlen(str[j])+1));
    strcpy ( lov_reset_values[reset_count], (str)[j] );
    printf ( “lov_reset_values[%d] = %sn”, reset_count, lov_reset_values[reset_count]);
    reset_count = reset_count + 1;
    }
    }

    printf (” reset_count = %dn”, reset_count );

    /*
    for ( inx = 0; inx < reset_count; inx++ )
    {
    printf ( “lov_reset_values[%d] = %sn”, inx, lov_reset_values[inx] );
    }
    */

    return stat;
    }

  • #3599

    What type of sort are you using ? I would just sort , count unique instances , allocate enough memory to hold the unique instances and copy the data ……

You must be logged in to reply to this topic.

0 Shares
Share
+1
Tweet
Share
Stumble