c - 消除无序数组中的重复元素

标签 c pointers dynamic-memory-allocation

编写函数: int 不同(int input[], int size, int **vetout); 当给定一个具有维度大小的整数数组输入时,会在动态内存中创建一个 vector ,其中包含重复一次的输入的所有元素。函数 different 返回修改后的数组的大小。 我的问题是,当我编译程序时,出现段错误错误。任何人都可以帮助我吗?

 #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;
}

最佳答案

我修改了您的函数,请随意使用它作为基础 - 这不是您问题的最佳解决方案 - 评论几乎涵盖了原始实现中的问题

希望这能作为指导

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;
}

关于c - 消除无序数组中的重复元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49490853/

相关文章:

c - 如何在 header 中声明外部二维数组?

c - 在 C 中初始化 2D/3D 数组的简写方法?

c - eclipse - "This project is not a CDT project"

c++ - 抛出 'std::logic_error' What() 的实例后调用终止: basic_string::_S_construct null 无效

c - 使用C中的线程表示路由表-作业任务

C如何判断一个char**占用多少内存

c - 在 C 中的结构中调整数组的大小

c - 为什么这个分配做得不好?

c++ - 检索函数内用 operator new 分配的类指针对象成员的值的问题

c++ - 内存泄漏预防 C++(我是对还是错?)