2017-01-30 6 views
-1

と私はちょうどそれがうまくいけない理由を理解できません。 は、ここに私の関数である。私は2つの配列の交差を見つける関数を書こうとしました

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

この関数はコンパイルが、私はそれを実行したときに動作しません。

+2

されていませんでした。それは何をするためのものか?あなたは何をすると思いましたか? –

+2

また、なぜ 'res'を同じサイズに保つために' realloc'を呼び出すのですか? –

+0

'realloc()'のマンページをもう一度読むことをお勧めします。 – EOF

答えて

-1

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

の指示に従ってください - この場合のexpceting出力は{2,3}です。交点には、両方の配列に複数回現れる要素も含まれていなければなりません。 – TOM1994

+0

sizeResが1になるたびに、配列内に1つのメモリセルを追加するためにreallocateを呼び出します。 – TOM1994

+0

同じ要素を見つけるたびにメモリを再割り当てすると何が問題になるのですか?なぜ新しく作成された配列にはその中の迷惑商品ですか?どのように修理すればいいですか? – TOM1994

関連する問題