【问题标题】:difficulties in writing function which returns the intersection of two arrays编写返回两个数组交集的函数的困难
【发布时间】:2017-01-31 15:54:19
【问题描述】:

我试图写一个函数来找到两个数组的交集

我只是不明白为什么它不能很好地工作。这是我的功能:

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)); --> res = realloc(res, (*sizeRes + 1) * sizeof(int));
  • 建议最初分配size1 * sizeof int 和size2 * sizeof int 的最小值。这是您可能需要的最大值。如果您愿意,在您知道所需大小时,在循环之后缩小该分配。作为奖励,如果交集为空,则 realloc()ing 将大小设为零会释放整个分配,从而修复当前代码遭受的内存泄漏。
  • 还有return NULL;:你有内存泄漏。
  • 在调用realloc() 时,始终将返回值保存到临时指针中,然后检查 (!=NULL) 该指针以确保操作成功。否则当realloc()失败时,原始指针丢失,导致不可恢复的内存泄漏

标签: c arrays dynamic-memory-allocation


【解决方案1】:
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。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 2018-09-09
    相关资源
    最近更新 更多