Loop through all array elements and compare each element; if all elements are the same, consider the arrays equal. Or use memcmp , which essentially does this.
Dave Sinkula
long time no c
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
>Or use memcmp, which essentially does this.
memcmp uses a shallow byte-by-byte comparison, so depending on the type of items in the array this might not be a good idea.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
>Or use memcmp, which essentially does this.
memcmp uses a shallow byte-by-byte comparison, so depending on the type of items in the array this might not be a good idea.
I know what you are saying, but would you mind listing examples.
Dave Sinkula
long time no c
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
>I know what you are saying, but would you mind listing examples.
The simplest example is an array of pointers. Do you want to compare the value of the pointers or the value of the addresses pointed to:
#include <stdio.h>
#include <string.h>
int main ( void )
{
static int a = 10;
static int b = 20;
static int c = 10;
static int d = 20;
int *aa[2] = { &a, &b };
int *ab[2] = { &c, &d };
if ( memcmp ( aa, ab, 2 * sizeof ( int ) ) == 0 )
puts ( "Equal" );
else
puts ( "Not equal" );
return 0;
}
Most likely it's the former, so memcmp would give the wrong answer unless by some coincidence both arrays all have pointers that reference the same addresses.
>It'll be something like this
No it wouldn't, that code is awful. The concept is sound, but the implementation sucks. Here are a few reasons why:
>#include
Not C++.
>#include
No portable.
>void main()
Undefined.
>clrscr();
VERY nonportable.
>cin>>n;
Not robust.
>for(i=1;i<=n;i++)
Poor style, not idiomatic.
>cin>>a[i];
Not robust, difficult to recover from on error.
>g=1;
>while(g==1)
>{ g=0;
Confused and awkward.
>getch();
Not portable and stupid because there's a standard alternative that works just as well.
And on top of that, you didn't use code tags...
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
>i just learn c++ programming. so i only can get this...
Then don't accept poor code. Try this for the comparison instead:
#include <iostream>
bool is_equal ( int a[], int b[], int size )
{
for ( int i = 0; i < size; i++ ) {
if ( a[i] != b[i] )
return false;
}
return true;
}
int main()
{
int a[] = {1,2,3,4,5,6,7,8,9};
int b[] = {1,2,3,4,5,6,7,8,9};
if ( is_equal ( a, b, 9 ) )
std::cout<<"They're equal"<<std::endl;
else
std::cout<<"They're not equal"<<std::endl;
}
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401