c语言中关于集合的小问题(求解)

这个是我的代码,但是有问题,能不能帮忙改一改

#include<stdio.h>
int common_elements(int length, int source1[length], int source2[length], int destination[length]) {
    int i = 0;
    int e = 0;
    while (i < length) {
        int a_i = 0;
        while (a_i < length) {
            if (source1[i] == source2[a_i] && source2[a_i] != destination[e] && source1[i] != destination[e]) {
                destination[e] = source1[i];
                e++;
                a_i++;
            }
            a_i++;
        }
        i++;
    }
    return e;
}
int main(void){
    return 0;
}

图片绿色的那行是正确的形式,红色的是我写的错误的形式。

img

图片显示的那一行应该是有问题的,但我不知道怎么改。

img

代码修改如下:

#include<stdio.h>
#include <stdlib.h>
int common_elements(int length, int source1[], int source2[], int destination[]) 
{
    int i = 0;
    int e = 0;
    int* p = (int*)malloc(sizeof(int)*length);
    for (i=0;i<length;i++)
        p[i] = 0;
    i = 0;
    while (i < length) 
    {
        int a_i = 0;
        while (a_i < length) 
        {
            if (source1[i] == source2[a_i] && p[a_i]==0) 
            {
                p[a_i] = 1;
                destination[e] = source1[i];
                e++;
                a_i++;
                break;
            }else
                a_i++;
        }
        i++;
    }
    free(p);
    return e;
}
int main(void){

    int source1[]={1,4,1,5,9,2};
    int source2[] ={1,1,2,3,5,8};

    int source3[] ={9,2,3,4,5,6,7,8,1,9};
    int source4[] ={3,1,4,1,5,9,2,6,5,3};

    int s3[6]={0};
    int s4[10]={0};
    int i,res1,res2;
    res1 = common_elements(6,source1,source2,s3);
    for (i = 0;i<res1;i++)
        printf("%d ",s3[i]);
    
    printf("\n");

    res2 = common_elements(10,source3,source4,s4);
    for (i = 0;i<res2;i++)
        printf("%d ",s4[i]);
    return 0;
}

这个问题的关键是要把已经确认相同的元素从原数组里去掉,这样第二次比较的时候就不会重复了。
但如果真的修改原数组比较麻烦,执行效率也不高。所以可以额外定义下标数组[0,1,2,3,4,5],发现有元素相同后,就把对应的下标改成-1,下次比较的时候把-1的跳过去。