简体   繁体   中英

Why doesn't this comparison between character arrays work?

char a[1][2];
char b[1][2];

a[0][0] = 'a';
a[0][1] = 'b';
b[0][0] = 'a';
b[0][1] = 'b';

if(a[0] == b[0]){
   cout << "worked\n";
}

So as far as I can tell, this comparison between arrays of characters doesn't work the way you would expect it to. The if statement does not execute because the condition a == b returns false. Why is this?

In this statement

if(a == b){
   cout << "worked\n";
}

a and b are implicitly converted to pointers to first elements of the corresponding arrays. So there is a comparison of two pointers. As the arrays occupy different areas in memory then the condition will be alwasy equal to false.

There is no such an operation as the comparison for arrays. To compare two arrays you have toc compare all elements of the arrays with each other. For example you could use standard algorithm std::equal. For example

if( std::equal( std::begin( a ), std::end( a ), std::begin( b ) ) ){
   cout << "worked\n";
}

Another approach is to use standard container std::array that has the comparison operator. For example

std::array<char, 2> a = { 'a', 'b' };
std::array<char, 2> b = { 'a', 'b' };

    if(a == b){
       cout << "worked\n";
    }

You can not compare arrays like that. You need to iterate over the arrays and compare each pair of elements in turn. Alternatively(and preferably) replace the static array with std::vector . The code you show compares the pointers a and b which of course are not equal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM