我在使用这样定义的函数时遇到了麻烦:
some_function(address_t const * const * my_addrs, uint8_t length)
wheareas address_t 定义为:
typedef struct
{
uint8_t addr_id : 1;
uint8_t addr_type : 7;
uint8_t addr[6];
} address_t;
我应该如何调用这个函数?
该代码来自蓝牙库,应该设置蓝牙地址的白名单。所以这个想法是用不同的 addr[6] 信息定义多个 address_t 结构。
非常感谢您的任何帮助
编辑:这里有更多信息
我有几个 addres_t 结构。它们的定义如下:
address_t addr1 = {.addr_id= 1, .addr_type = 3, .addr = {0x12,0x34,0x56,0x78,0x90,0xAB}};
address_t addr2 = ...
我可以将然后组合到一个数组,如:
address_t my_whitelist[6];
my_whitelist[0] = addr1;
my_whitelist[1] = addr2;
...
我不确定这是否需要。现在我必须将一些方法传递给这个函数。我希望这些进一步的信息有帮助。
最佳答案
How am I supposed to call this function?
示例调用
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 } };
注意
my_whitelist[]
的类型变化.这需要是一个指针数组。这些指针需要指向 const
数据归于 1st const
以上。 // 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];
通知
my_whitelist[]
不需要是 const
由于 2nd const
以上与 const address_t * const my_whitelist[6];
.此 2nd const
以上通知调用代码some_function()
不会修改 my_whitelist[]
的数组元素. return some_function(my_whitelist, len);
}
注意:如果
my_whitelist[]
是 const
数组,它的值不能被赋值但可以被初始化。// Example usage with a `const my_whitelist[]`
const address_t * const my_whitelist[] = { &addr1, &addr2, &addr3 };
注:
address_t const *
就像 const address_t *
.以 const
领先与 C 规范的风格相匹配。address_t const * const * my_addrs;
// same as
const address_t * const * my_addrs; // More common
关于c - c 语法问题 - const * const * 定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50002705/