Reputation: 5195
what is the best way to compare int arrays b and c with a:
int a[] = {0,1,0,0,1};
int b[] = {0,1,0,0,1};
int c[] = {1,1,0,0,1};
b and c are just examples, assume they can be any combination of 0s and 1s.
I am trying to detect arrays identical to a. I have googled this for a while and have not found a satisfactory answer.
This is a beginners question I realise, thank you for your patience.
Upvotes: 14
Views: 43529
Reputation: 70
For performance reasons memcmp() will compare byte for byte while int arrays are in 4 byte chunks. This will most likely be pretty slow if the array is large or you have to compare many arrays.
The simplest way is to run a for loop that exits as soon as you find a difference.
bool is_array_equal(const int * a, const int * b, length){
for (int i = 0; i < length; ++i){
if(a[i] != b[i]){ return false; }
}
return true;
}
Upvotes: 0
Reputation: 41
More information is needed on the question. I can divide your question in two ways as below,
Solution for Question no 1: One can use memcmp for this problem. Because memcmp will compare lexicographical and return 0 or 1 or -1 as below
#include<stdio.h>
#include<string.h>
int main()
{
char a[]={'a','b','c'};
char b[]={'a','b','c'};
int x=memcmp(a,b,sizeof(a));
printf("%d\n",x);
return 0;
}
***output:0***
#include<stdio.h>
#include<string.h>
int main()
{
char a[]={'a','c','b'};
char b[]={'a','b','c'};
int x=memcmp(a,b,sizeof(a));
printf("%d\n",x);
return 0;
}
***output:1***
#include<stdio.h>
#include<string.h>
int main()
{
char a[]={'a','b','c'};
char b[]={'b','a','c'};
int x=memcmp(a,b,sizeof(a));
printf("%d\n",x);
return 0;
}
***output:-1***
Solution for Question no 2: One can use memcmp for this problem, the best solution for this problem is as below
Here, I answered for the above problem https://stackoverflow.com/a/36130812/5206646
Upvotes: 1
Reputation: 67822
If you mean
int a[] = {0,1,0,0,1};
int b[] = {0,1,0,0,1};
int c[] = {1,1,0,0,1};
then
memcmp(a, b, sizeof(a)); /* returns zero for a match */
memcmp(a, c, sizeof(a)); /* returns nonzero for no match */
Upvotes: 6
Reputation: 363817
Use the standard memcmp
function from <string.h>
.
memcmp(a, b, sizeof(a)) == 0
whenever a
and b
are equal.
Upvotes: 33