9

I am trying to create QByteArray from std::vector.. I tried;

std::vector<uint8_t> buf;
QByteArray img = new QByteArray(reinterpret_cast<const char>(buf), buf.size());

However it gives error;

error: invalid cast from type 'std::vector<unsigned char, std::allocator<unsigned char> >' to type 'const char'

1 Answer 1

19

You need to cast buf.data() instead of buf:

QByteArray* img = new QByteArray(reinterpret_cast<const char*>(buf.data()), buf.size());
4
  • 4
    Note .data() is only available in C++11 and later. If your compiler doesn't support this, use &buf[0].
    – Saul
    Jun 29, 2015 at 11:00
  • when I use buf.data() it says error: cast from 'unsigned char*' to 'const char' loses precision
    – goGud
    Jun 29, 2015 at 11:39
  • ohh.. my mistake, I didnt use char pointer.. thank you very much
    – goGud
    Jun 29, 2015 at 11:40
  • I personally do avoid new and delete wherever I can. You can do on modern compilers like this: [auto img = QByteArray(reinterpret_cast<const char*>(buf.data()), buf.size());] May 27, 2020 at 7:55

Your Answer

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

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