Reputation: 83
I have troubles using a function that is defined like this:
some_function(address_t const * const * my_addrs, uint8_t length)
wheareas address_t is defined as:
typedef struct
{
uint8_t addr_id : 1;
uint8_t addr_type : 7;
uint8_t addr[6];
} address_t;
How am I supposed to call this function?
The code is from a bluetooth library and is supposed to set a whitelist of bluetooth addresses. So the idea is to define multible address_t structs with different addr[6] information.
Thank you very much for any help
edit: here are some more information
I have several addres_t structs. They are defined like this:
address_t addr1 = {.addr_id= 1, .addr_type = 3, .addr = {0x12,0x34,0x56,0x78,0x90,0xAB}};
address_t addr2 = ...
I can combine then to an array like:
address_t my_whitelist[6];
my_whitelist[0] = addr1;
my_whitelist[1] = addr2;
...
I'm not sure if this is needed or not. Now I have to pass this some how to this function. I hope this further information helps.
Upvotes: 4
Views: 105
Reputation: 153457
How am I supposed to call this function?
Example call
typedef struct {
uint8_t addr_id :1;
uint8_t addr_type :7;
uint8_t addr[6];
} address_t;
// 1st const, 2nd const
// v---v v---v
int some_function(address_t const * const * my_addrs, uint8_t length) {
(void) my_addrs;
(void) length;
return 0;
}
int foo() {
const address_t addr1 = { .addr_id = 1, .addr_type = 3, .addr = { 1,2,3,4,5,6 } };
const address_t addr2 = { .addr_id = 1, .addr_type = 3, .addr = { 1,2,3,4,5,6 } };
const address_t addr3 = { .addr_id = 1, .addr_type = 3, .addr = { 1,2,3,4,5,6 } };
Notice the type change of my_whitelist[]
. This need to be an array of pointers. Those pointers need to point to const
data due to 1st const
above.
// address_t my_whitelist[6];
const address_t *my_whitelist[6];
my_whitelist[0] = &addr1;
my_whitelist[1] = &addr2;
my_whitelist[2] = &addr3;
my_whitelist[3] = &addr1;
my_whitelist[4] = &addr2;
my_whitelist[5] = &addr1;
uint8_t len = sizeof my_whitelist / sizeof my_whitelist[0];
Notice my_whitelist[]
does not need to be const
due to the 2nd const
above as with const address_t * const my_whitelist[6];
. This 2nd const
above informs the calling code that some_function()
will not modify the array elements of my_whitelist[]
.
return some_function(my_whitelist, len);
}
Note: If my_whitelist[]
was a const
array, its values cannot be assigned yet can be initialized.
// Example usage with a `const my_whitelist[]`
const address_t * const my_whitelist[] = { &addr1, &addr2, &addr3 };
Note: address_t const *
is like const address_t *
. Leading with const
matches the style of the C spec.
address_t const * const * my_addrs;
// same as
const address_t * const * my_addrs; // More common
Upvotes: 2