+ 5

Array

How to compare two array? Is it possible to make dynamic array size in c?

24th Oct 2018, 4:55 AM
Solo S
Solo S - avatar
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" ;
24th Oct 2018, 8:20 AM
blACk sh4d0w
blACk sh4d0w - avatar
+ 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
25th Oct 2018, 5:21 AM
Babak
Babak - avatar
+ 5
As far as I know you can't make dynamic array in c. you can try in python
24th Oct 2018, 5:03 AM
Coder
Coder - avatar
+ 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.
24th Oct 2018, 5:49 AM
Ipang
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; }
25th Mar 2020, 11:15 PM
ANGAJALA SAISRI
ANGAJALA SAISRI - avatar