编写函数: 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/