+ 5
Array
How to compare two array? Is it possible to make dynamic array size in c?
5 Respostas
+ 12
We can create dynamic array in C
int size = 0;
cin >> size ;
int *arr = malloc(size * sizeof(int)) ;
To compare two arrays, the size of both arrays must be same
Here's how you compare two arrays:
bool isEqual = false ;
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
if(arr1[i] == arr2[j])
{
isEqual = true ;
break ;
}
}
}
if(isEqual)
cout << "Arrays are not equal" ;
+ 6
nAutAxH AhmAd
Just one catch. The holy ritual of checking for NULL before using a dynamically allocated storage can't be taken too lightly!
int *arr = malloc(size * sizeof(int));
if (arr == NULL)
exit(1); // or for more portable code using exit(EXIT_FAILURE) or return EXIT_FAILURE or as a custom error handling mechanism, showing a message regarding the failure of the allocation and then return an error code like so "return -1"
And also the importance of freeing up the memory should be emphasized since a lot of newbies have the tendency to forget it at the end of the day.
_____
https://en.cppreference.com/w/c/program/EXIT_status
+ 5
As far as I know you can't make dynamic array in c. you can try in python
+ 5
Just an idea:
* Check number of elements, if number of elements differs, the arrays are different.
* If they have same number of elements then iterate through the arrays with a loop, all the while checking whether arr1[n] == arr2[n]. At any iteration break the loop if the check evaluates to false.
0
#include<stdio.h>
int main()
{ int array1[1000],array2[1000],flag=0;
int n1,n2,i;
printf("enter the size of array1\n");
scanf ("%d/n",&n1);
printf("enter the size of array2\n");
scanf ("%d/n",&n2);
// be careful that the n1and n2should be same for comparing
for(i=0; i<n1; i++)
{scanf("%d",&k1[i]);
scanf("%d",&k2[i]);}
for(i=0; i<n1; i++)
{ if(k1[i]==k2[i])
;
else
flag=1;
}
if (flag==0)
printf("the two arrays are equal/n");
else
printf("the two arrays are not equal/n");
return 0; }