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
To create a vector you need to know the size of the vector. So you can create a vector from an array because you know the size of the array.
But you don't have an array, you have a pointer. You cannot know the size of an array from a pointer, so your task is impossible from the information you have given.
Now maybe you have some other way to know the size of the array, if you do then you can create the vector. Please update the question if appropriate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With