You have a pointer of type unsigned char*
pointing to an array.
Then you want to push every element of the array into a std::vector<unsigned char>
, right?
If so, the key is to know the size of the array. You need to know the size beforehand. There's no way to determine the size of the array in the general case with some keyword or function if all that is visible to you is a pointer of type unsigned char*
. You need to pass that information along with the pointer somehow.
In the case when the pointer of type unsigned char*
points to an array of characters which is null-terminated (e.g. {'f', 'o', 'o', '\0'}
), then you can use the C-string function strlen
to count the number of characters in the array using only the pointer. However if the array is not null-terminated this will result in undefined behaviour.
When you have the size
it's a simple matter to populate the std::vector
with the arrays elements:
std::vector<unsigned char> v(arr, arr + size); // arr = pointer to array.
This is why you should use the containers in the standard library instead of raw arrays, as these containers internally keep track of the size and you can always access it with the size()
function.
For constant size arrays use std::array
. Example:
std::array<unsigned char, 3> arr{'f', 'o', 'o'}; // arr.size() == 3
// Print its contents.
for (auto c : arr) {
std::cout << c << std::endl;
}