5

I am trying to perform a comparison of elements in:

std::vector<std::array<uint8_t, 6> > _targets =
{
  { 0x00, 0x00, 0x00, 0x00, 0x00, 0x11 }
  { 0x00, 0x00, 0x00, 0x00, 0x00, 0x22 }
};

to a traditional array:

 uint8_t _traditional[6] =  { 0x00, 0x00, 0x00, 0x00, 0x00, 0x33 }

as:

  for (auto target : _targets) 
  {

     if (! memcmp(target, _traditional, 6)) {
        known = 1;
     } 
  }

and am receiving a data conversion error:

error: cannot convert 'std::array<unsigned char, 6u>' to 'const void*' for argument '1' to 'int memcmp(const 
void*, const void*, size_t)

What is the propert byte wise comparison operation I can perform to accomplish equality evaluation?

4
  • 1
    why not make _traditional also a std::array and use ==? Aug 9, 2018 at 23:25
  • @Cheers is there a way to temporarily cast it? its part of a large 3rd party library I leveraging
    – Rice
    Aug 9, 2018 at 23:26
  • 3
    How about std::equal?
    – Kerrek SB
    Aug 9, 2018 at 23:29
  • 1
    Careful with those leading underscores. Sometimes they mean something special. [What are the rules about using an underscore in a C++ identifier?](stackoverflow.com/questions/228783/… Aug 9, 2018 at 23:33

1 Answer 1

8

You can use the data() member of array to get a pointer to the contained array:

if (! memcmp(target.data(), _traditional, 6))

The alternative of using &target[0] will work in this case (where you're storing a uint8_t) but won't work if you store a class that overloads the unary & (address) operator. But you could use std::addressof(target[0]) which will work even in the presence of an overloaded address operator.

5
  • One of those cases where it should work unless the implementer of std::array was insane or solving a very interesting problem` Aug 9, 2018 at 23:31
  • Just out of idle curiosity, but could you replace target.data() with &target[0] ?
    – dgnuff
    Aug 9, 2018 at 23:32
  • In addition to target.data() only &target[0] is guaranteed to work. afaik (possibly &target too but not certain tbh).
    – Galik
    Aug 9, 2018 at 23:43
  • @galik If the type stored has overridden & then &target[0] may differ from target.data(), otherwise it won't differ. Aug 10, 2018 at 0:29
  • @Yakk-AdamNevraumont Well the question is asking about uint8_t, otherwise memcmp would be dicing it.
    – Galik
    Aug 10, 2018 at 0:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.