I was trying to write a program that reads two arrays (and their sizes), writes the numbers that appear in both in a new array and returns the new array and it's size.
it throws me out after reading the arrays. I think I did a few things wrong with the dynamic memory allocation, still very confused by the whole thing.
I'd appreciate it if you could take a look and tell me what's wrong. thanks!
#include <stdio.h>
#include <stdlib.h>
int andArrays(int*, int*, int, int, int*);
void main()
{
int size1, size2, i, j, s, num1, num2, newsize;
printf("enter the size of the array >>> ");
scanf_s("%d", &size1);
int* arr1 = (int*) malloc(size1*sizeof(int));
printf("enter %d numbers: ", size1);
for (i = 0; i < size1; i++)
{
scanf_s("%d\n", &num1);
arr1[i] = num1;
}
printf("enter the size of the array >>> ");
scanf_s("%d", &size2);
int* arr2 = (int*)malloc(size2*sizeof(int));
printf("enter %d numbers: ", size2);
for (j = 0; j < size1; j++)
{
scanf_s("%d\n", &num2);
arr2[j] = num2;
}
int newarray = andArrays(&arr1, &arr2, size1, size2, &newsize);
printf("size of new array is: %d", newsize);
for (s = 0; s < newsize; s++)
printf("%d", newarray[s]);
free (newarray);
free(arr1);
free(arr2);
}
int andArrays(int* arr1, int* arr2, int size1, int size2, int* newsize)
{
int i = 0, j = 0, num, f = 0;
int* newarr = (int*)malloc(size1 * sizeof(int));
while (1)
{
if (arr1[i] == arr2[j])
{
num = arr1[i];
newarr[f] = num;
f++;
}
i++;
j++;
if (i == size1)
break;
}
*newsize = f;
}
}