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

标签 c arrays

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

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;
}

这个函数可以编译,但是当我运行它时不起作用。

最佳答案

1- 每次找到相同的元素时,您都会重新分配内存,这样新创建的数组中就会有垃圾项。要查看此分配一些内存并查看分配的内存的内容

这是新代码,我更改的只是内存分配

#include "stdafx.h"
#include "malloc.h"
#define min(a, b)  (((a) < (b)) ? (a) : (b)) 

int* IntersectionOfArrays(int* arr1, int size1, int* arr2, int size2, int* sizeRes) 
{
    //allocating memory for the output array, it's at most the size of the smaller array
    int * res = (int*)malloc(min(size1,size2)*sizeof(int));

    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)++;
        }   
    }

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

    return res;
}

int _tmain(int argc, _TCHAR* argv[])
{
    int array1[]={1,2,2,2,3};
    int array2[]={1,2,3,4,5,6,7};

    int sizeRes = 0;

    int * output = IntersectionOfArrays( array1, 5, array2, 7, &sizeRes );
    return 0;
}

关于c - 我试图编写一个函数来查找两个数组的交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41946378/

相关文章:

javascript - 为什么数组显示为 1D 而不是 2D 但表格有效?

php - 基于父子关系对数组进行排序的算法

c - 在结构体中写入数组

C 不兼容的整数到指针转换,将 'int' 传递给类型 'const char *' 的参数;

c - 缩小位图字体的算法

java - JAVA中创建与char数组对应的数组

c - 后缀表达式 (type-name){initializer-list}

c - 前置子进程控制台输出

javascript - 从数组中删除项目会跳过某些项目

javascript - 数组到元素 javascript