I am having trouble converting a pointer array of uint16_t to std::vector<uint16_t> because of integer size issues.
auto *arr = static_cast<const uint16_t *>(some_method.getArray());
std::vector<uint16_t> vec(arr, sizeof arr / sizeof arr[0]);
In the first line I obtain a const uint16_t*
array. In the second line I initialize the vector using the iterator constructor and pass in the pointer array arr
and length of the array (size of the array divided by size of the first element = length of array).
However, c++ wants me to cast arr to unsigned long
. So here it is with the cast
std::vector<uint16_t> vec((unsigned long) arr, sizeof arr / sizeof arr[0]);
It seems to me something bad will happen casting from uint16_t (2 bytes) -> unsigned long (4 bytes) -> uint16_t (2 bytes). Is there a better way to do this array conversion?
Edit: Thank you all for the valuable feedback, the main issues I had:
sizeof gets the size of the pointer, not the length of the array.
I was using the wrong constructor