c - 编写返回两个数组交集的函数的困难

标签 c arrays dynamic-memory-allocation

我尝试编写一个函数来查找两个数组的交集

我只是不明白为什么它不能正常工作。这是我的功能:

int* IntersectionOfArrays(int* arr1, int size1, int* arr2, int size2, int* sizeRes) 
{
    int* res=(int*)malloc(1*sizeof(int));  //res is the array of the resolution of intersection//
    int i = 0, j = 0;
    *sizeRes = 0;

    merge_sort(arr1,0, size1-1);  //sorting the arrays//
    merge_sort(arr2,0, size2-1);

    while (i < size1 && j < size2) 
    {
        if (arr1[i] < arr2[j])
            i++;
        else if (arr1[i] > arr2[j]) 
            j++;
        else 
        {   
        res[*sizeRes] = arr1[i]; //getting the same elements of the two arrays - the intersection values//
        i++;
        j++;
        (*sizeRes)++;
        res = (int*)realloc(res, 1*sizeof(int)); //allocating more memory as required - according to the size of res(intersection)//
        }   
    }

    if (*sizeRes==0)  //if the intersection is empty 
        return NULL;
    return res;
}

此函数可以编译,但无法按预期工作,因为我得到了垃圾项目.. 我想知道这个功能应该如何修复。

最佳答案

res = (int*)realloc(res, 1*sizeof(int)); 
//allocating more memory as required - according to the size of res(intersection)//

但是与您的评论所暗示的相反,您并没有增加数组的大小。但是相反,您再次只为一个整数分配内存。尝试以下操作:

res = realloc(res, (*sizeRes + 1) * sizeof(int));

此外,在使用 realloc() 时使用临时指针

int* temp = realloc(res, (*sizeRes + 1) * sizeof(int));
if(temp == NULL) {
    //handle unsuccessful memory reallocation
}
else {
    res = temp;
}

通过这样做,即使重新分配失败,您也可以使用 res

关于c - 编写返回两个数组交集的函数的困难,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41961821/

相关文章:

可展开二次方程的C程序

c - 将两个不同的结构传递给同一个函数

java - 从java中的未排序数组中获取未使用数字的列表

c++ - 当指向动态分配的内存时,指向指针的指针会分配什么值?

c - 使用 realloc() 时的 SIGABRT

c - 读入 char 并判断是否有空格或换行符 C

c - 变量的含义(传递给函数)

javascript - 在数组中查找元素并返回父元素

java - 无法将字符串转换为 JsonArray

c++ - C++ 单例类实例的堆/动态与静态内存分配