Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equality & assignment operators used on arrays in C++

I was given a homework question that really confuses me. The question is:

In C++ the equality test == may be applied to arrays, but the assignment operator = cannot be applied to arrays. Explain why.

This confuses me, because my understanding is that the == operator would just compare the addresses of the first two elements (which if two arrays were in fact held in separate memory locations, of course would be different). And the = operator, when used like array1 = array2; would just cause array1 to point to the same memory location as array2 does.

What am I missing here? It seems as though either operator can be used, but neither would produce the results typically intended by those operators.

like image 965
Adam S Avatar asked Mar 17 '11 21:03

Adam S


1 Answers

my understanding is that the == operator would just compare the addresses of the first two elements

This is correct: if you compare two arrays using ==, it will compare the addresses of the arrays, so it will only yield true if you compare an array with itself (or with a pointer to an element of the same type). See the description below for why.

the = operator, when used like array1 = array2; would just cause array1 to point to the same memory location as array2 does.

This is not correct because an array is not a pointer. array1 can't point to the same memory location as array2 because array1 isn't a pointer, it's an array of elements.

An array is a sequence of elements. In most contexts, the name of an array is implicitly converted to a pointer to its initial element. This is why you can do things like:

void f(int*);

int data[10];
int* p = data; // this is the same as 'int* p = &data[0];'
f(data);       // this is the same as 'f(&data[0]);'

array1 = array2; won't work because arrays are not assignable (mostly for historical reasons; I've never heard a convincing technical reason why it isn't allowed: it was never allowed in C, and C has been around for decades. There's some discussion of this in the comments and answers to Why does C support memberwise assignment of arrays within structs but not generally?).

The following program will not compile:

int main() {
    int a[10], b[10];
    a = b;
}

For an "assignable" array, you can use the array container-like class found in Boost (boost::array), C++ TR1 (std::tr1::array), or C++0x (std::array). It is actually a class that contains an array; it can be copied and it provides many of the benefits of the Standard Library containers plus the performance characteristics of an array and the ability to use its data as an array when you need to.

like image 118
James McNellis Avatar answered Oct 03 '22 01:10

James McNellis