我尝试编写一个函数来查找两个数组的交集
我只是不明白为什么它不能正常工作。这是我的功能:
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/