我只是不明白为什么它不能很好地运作。 这是我的功能:
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;
}
此函数编译,但在运行时不起作用。
答案 0 :(得分:-1)
1-每次找到相同的元素时都会重新分配内存,这样新创建的数组中就会有垃圾项。要看到这个,请分配一些内存并查看已分配内存的内容
这是新代码,我改变的只是内存分配
User, City, Other Given Cities