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?

Rice
  • 3,371
  • 4
  • 19
  • 23
  • 1
    why not make `_traditional` also a `std::array` and use `==`? – Cheers and hth. - Alf Aug 09 '18 at 23:25
  • @Cheers is there a way to temporarily cast it? its part of a large 3rd party library I leveraging – Rice Aug 09 '18 at 23:26
  • 3
    How about [`std::equal`](https://en.cppreference.com/w/cpp/algorithm/equal)? – Kerrek SB Aug 09 '18 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?](https://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier] – user4581301 Aug 09 '18 at 23:33

1 Answers1

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.

1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56
Coral Kashri
  • 3,436
  • 2
  • 10
  • 22
  • One of those cases where it should work unless the implementer of `std::array` was insane or solving a very interesting problem` – user4581301 Aug 09 '18 at 23:31
  • Just out of idle curiosity, but could you replace `target.data()` with `&target[0]` ? – dgnuff Aug 09 '18 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 09 '18 at 23:43
  • @galik If the type stored has overridden `&` then `&target[0]` may differ from `target.data()`, otherwise it won't differ. – Yakk - Adam Nevraumont Aug 10 '18 at 00:29
  • @Yakk-AdamNevraumont Well the question is asking about `uint8_t`, otherwise `memcmp` would be dicing it. – Galik Aug 10 '18 at 00:47