Pass uint16_t array into function that takes uint8_t*

3.5k views Asked by At

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?

1

There are 1 answers

1
Red Alert On BEST ANSWER

When you say uint16_t d[10];, you are defining an array d. When you say d[0], you access the first element of that array, which is of type uint16_t. The function is expecting a pointer, so you should cast a pointer to your array, not an element in it:

fctn( (uint8_t*)d, 10*sizeof(uint16_t) );

When you do this, d is decayed from type uint16_t[10] to uint16_t*, then cast to uint8_t* before being passed to fctn.

As an aside, you can also use sizeof(d) to simplify your length calculation:

fctn( (uint8_t*)d, sizeof(d) );

Note that this only works if d is declared as an array (on the stack).