0

I've got std::vector<unsigned char> data = {0x00,0x00,0x00,0x01}; - the function I'm passing this to requires unsigned char * - I do the following : unsigned char * converted = static_cast<unsigned char*>(data.data()); and I then pass converted to the function. I'll be using that extensively throughout the code. I prefer to work with vectors as I find them easier to handle. Now the question is - is that cast safe - I mean can I count on it that it'll always work or is it a slow or a bad approach? If so, what's a better way to do it?

regards.

ZoOl007
  • 407
  • 3
  • 22
  • Nothing really wrong, given the fact that you haven't given us much code to judge on. – DeiDei Jun 09 '16 at 19:51
  • I figure you know not to resize the vector. –  Jun 09 '16 at 19:53
  • 3
    It doesn't look like the cast is even necessary to me... `data()` returns an `unsigned char*` – kmdreko Jun 09 '16 at 19:53
  • `std::vector::data()` returns a non-const `T*` if called on a non-const `vector` object, so you don't need the cast: `unsigned char * converted = data.data();` However, if you have a const `vector` object (say, an input parameter to a function), you can use `const_cast` instead: `unsigned char * converted = const_cast(data.data());` Though this is not advisable if you can avoid it. – Remy Lebeau Jun 09 '16 at 19:57

2 Answers2

7

What about

 std::vector<unsigned char> data;
 unsigned char* converted = &data[0];

?

VolAnd
  • 6,367
  • 3
  • 25
  • 43
1

(data.size()? &data.front():nullptr) avoids any need for a cast.

  • even better... works a charm - thank you people - the better I get the more I realise how little I know... – ZoOl007 Jun 09 '16 at 20:11