0

I'm copying an array, and for some reason the values aren't the same after the copy. The code is below. In both cases, the _data variable is a char[4]. After the copy, the assert fires. If I examine the two values in the debugger, they show as: 0x00000000015700a8 and 0x00000000015700b0.

_data[0] = rhsG->_data[0];

_data[1] = rhsG->_data[1];

_data[2] = rhsG->_data[2];

_data[3] = rhsG->_data[3];

assert(_data == rhsG->_data);
Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
Nick Sephton
  • 81
  • 1
  • 8

5 Answers5

2

You've made the mistake of thinking C++ is an easy-to-use high-level language (joke). operator == on C-style arrays compares their address, which of course is different here. You can use std::equal to compare the two arrays, or use a different data structure which supports a more intuitive opeartor ==, such as std::array or std::vector.

You could then also use their operator = to copy them, instead of each element one at a time, assuming the source and destination are the same size. There is std::copy if they are not, or they must be C-style arrays.

Neil Kirk
  • 21,327
  • 9
  • 53
  • 91
2

If comparing with == you are just comparing two pointers, which value are different. If you want to compare for equality two arrays, you can use memcmp()

assert( ! memcmp(_data, rhsG->_data, 4) );
drodri
  • 5,157
  • 15
  • 21
2

When you use operator == in assert "_data == rhsG->_data", _data and rhsG->_data are both represented address of the array. So, in your debugger, 0x00000000015700a8 is array address of _data and 0x00000000015700b0 is array address of rhsG->_data. Obviously, they are different, then the assert fires. After all, array name is always a pointer that point to the first array address in memory.

Tianjipeng
  • 43
  • 4
1

"_data == rhsG->_data" does not compare the individual elements of two arrays.

The "==" operator is not defined for arrays, so the two parameters are decayed to pointers, which == can work on.

Community
  • 1
  • 1
Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
0

Your assert is comparing the addresses of the two arrays which are different because they are in different memory locations.

If you really want to compare the values, then either loop over them or use memmp.

assert(memcmp(_data, rhsG->_data, 4) == 0);
merlin2011
  • 71,677
  • 44
  • 195
  • 329