Reputation: 17360
How can i pass a buffer of unsigned ints, to a function expecting a buffer of unsigned chars? The function will operate and update the buffer. Next is the pseudo-code of what I am trying to achieve.
unsigned int* inputBuffer = (unsigned int*)malloc(bufferSize);
function(inputBuffer); <- How to perform this correctly?
bool function(unsigned char *buffer)
{
...operate and update values of buffer
}
Upvotes: 0
Views: 174
Reputation: 363627
It depends on what the function does. If it operates on the bytes in the buffer (like memcpy
, memcmp
etc. do), then just cast the pointer:
function((unsigned char *)inputBuffer);
If the function operates on the elements (integers) in the buffer, then you'll have to copy the entire contents into a temporary buffer:
size_t nelems = bufferSize / sizeof(unsigned int);
unsigned char *temp = malloc(nelems);
if (temp == NULL)
// handle error
for (size_t i=0; i < nelems; i++)
temp[i] = (unsigned char)(inputBuffer[i]);
function(temp);
// copy results back into inputBuffer
free(temp);
However, if you find that you need to do something like this, then there's probably a design flaw somewhere in your program. You simply shouldn't have to do this, ever, unless you're working with a poorly designed library.
Upvotes: 1
Reputation: 1216
An int and a char are different sizes. Passing an array of ints to a function expecting an array of chars will cause that function to treat each int as (not necessarily but usually) 4 chars. You will need to either restructure the rest of your code to work with char arrays, or to create a temporary char array, copy each element to it, then call the function and copy each element back.
However, the question of "why would you ever want to do this" (H2CO3's comment) still stands; different situations call for different solutions.
Upvotes: 0