Question

I have following in my code:

static unsigned char* table;
...
table = something here;

Now I have to assign this table to variable of type std::vector<unsigned char> and I am unable to do so. I am doing:

unsigned char* buffer = (unsigned char*) table;
std::vector<unsigned char>::size_type size = strlen((const char*)buffer);
std::vector<unsigned char>static rawTable(buffer, buffer + size);
for(ByteBuffer::iterator it=rawTable.begin();it!=rawTable.end();++it)
    std::cout << "Raw Table: "<<*it<< std::endl;

I am able to compile the code, but no value is there inside rawTable. Please help! I have verified that variable table has value. I appreciate any help on this. Thanks.

Was it helpful?

Solution

strlen gives you the length of a string, not the size of an arbitrary memory region. If your table has a '\0' anywhere inside, strlen will find it and stop counting.

Also, by making rawTable a static variable, it will not update its value if buffer or size ever change. static variables are constructed only once.

Also, if this is supposed to be a table of numeric data, you should cast to a numeric non-character type. Otherwise cout may interpret it as ASCII codes.

OTHER TIPS

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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top