In C, I'd like to pass a uint16_t array into a function that takes uint8_t:
bool fctn(uint8_t *data, size_t length);
I have this array, which is inside a struct:
typedef struct sStruct sStruct;
struct sStruct{
uint16_t d[10];
}
sStruct myStruct;
So I do:
void test(sStruct structData) {
fctn( (uint8_t*)structData->d[0], 10*sizeof(uint16_t) );
}
The length isn't the issue here, it's passing the array. If this array weren't a pointer already I'm getting "error: cast to pointer from integer of different size", how can I make it look like an array of uint8_t? As far as that function is concerned, a uint16_t array will just look like a double length array of size uint8_t, but I'm not sure how to tell the compiler this...when the input is already a pointer.
If array 'd' wasn't inside a struct, but say just a global, I'd just do
fctn( (uint8_t*)d, 10*sizeof(uint16_t) );
What's the right way to do the function pass for an array inside a passed struct?
When you say
uint16_t d[10];
, you are defining an arrayd
. When you sayd[0]
, you access the first element of that array, which is of typeuint16_t
. The function is expecting a pointer, so you should cast a pointer to your array, not an element in it:When you do this,
d
is decayed from typeuint16_t[10]
touint16_t*
, then cast touint8_t*
before being passed tofctn
.As an aside, you can also use
sizeof(d)
to simplify your length calculation:Note that this only works if
d
is declared as an array (on the stack).