0

I would like to cast a vector<uint8_t>& of binary data to a vector<int16_t>& preferably without copying any data. Running the code below (compiled with gcc 9.4.0) I find that the size of data16 is 3. Is casting vector pointers with types of different sizes safe or does it produce undefined behaviour?

#include <cinttypes>
#include <iostream>
#include <vector>

int main()
{
    std::vector<uint8_t> data8 = { 0, 0, 0, 0 };
    std::vector<int16_t>& data16 = *reinterpret_cast<std::vector<int16_t>*>(&data8);
    std::cout << data16.size() << std::endl;
}```
  • 3
    You can't do it. You'll get UB even if types have the same size. – Evg Apr 03 '22 at 09:38
  • It is not safe if they have the same size either. Use of any such cast, even `std::vector` to `std::vector`, has undefined behavior. – user17732522 Apr 03 '22 at 09:39
  • 1
    Since a vector is guaranteed to be continuous, you can take a T1*. Now whether T1* can be safely converted to T2* is another issue. In case of byte <-> short then you have 2 bytes creating 1 word. However converting this to a vector is not a good idea - you can't "attach" a vector to an array. – Michael Chourdakis Apr 03 '22 at 09:51

0 Answers0