Search code examples
cpointersdynamic-memory-allocation

Eliminate duplicated elements from a non-ordered array


Write the function: int different(int input[], int size, int **vetout); while given an array input of integers with dimension size creates a vector in dynamic memory that contains all the elements of input repeated once. Function different returns the size of the modified array. My problem is that i get the segmentation fault error when i compile the program. Can anyone help me please.

 #include<stdio.h>
 #include<stdlib.h>

int different(int input[],int size, int **vetout);

int main(){
    int input[]={1,1,2,3,4,4,1,2,3,4};
    int size=10; int n; int i; int *vetout;
    n = different(input, size, &vetout);
    printf("The size is : %d", n);
    for(i=0;i<n;i++){printf("The array is : %d",vetout[i]);}
    return 0;
}

int different(int input[],int size, int **vetout){
    int i=0;int j,k;
    while(i<size){
        j=i+1;
        while(j<size){
            if(input[i]==input[j]){
                for(k=j;k<=size;k++){
                    input[k]=input[k+1]; size--;
                }
            }
            j++;
        }
        i++;
    }

    *vetout=(int *)malloc(sizeof(int)*size);
    printf("The size is : %d",size);
    for(i=0;i<size;i++){*vetout[i]=input[i];}

    return size;
}

Solution

  • I modified your function, feel free to use it as a base - this is not the best solution for your issue - the comments preety much covered your issues in the original implementation

    hope this will serve as a guideline

    int different(int input[],int size, int **vetout){
    
        int count = 0;
        int found, i, j;
        *vetout = malloc(sizeof(int)*size);
    
        for ( i=0; i<size ; i++ ) {
            // this loop will iterate on each element of the array
            // and check if it was already listed
            found = 0;
            for ( j=0; j < count ; j++ ) {
                //this loop checks if the value was already set in the output vector
                if ( *(*vetout+j) == input[i] ) {
                    found = 1;
                }
            }
    
            //if it was not set - then set it and increse the index 'count'
            if ( !found )
            {
                *(*vetout+ (count++)) = input[i];
            }
        }
    
        printf("The size is : %d\n", count);
    
        return count;
    }