c - c 语法问题 - const * const * 定义

标签 c pointers syntax parameters constants

我在使用这样定义的函数时遇到了麻烦:

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/

相关文章:

vb.net - 当我在我的数学运算中放置一个 "="符号时发生了什么?

c - 为什么我不能在 C 中使用一维数组的输入值?

c - 在 Linux 编程中通过管道在进程之间发送链表结构的最佳方法是什么

ios - 在 Swift 中从 NSData 中提取结构

c++ - 谁应该拥有指针

c - 为什么某些 C 字符串库函数(即 strtok)不接受尚未使用 malloc 分配的 char *?

c++ - 对于 C/C++,什么时候不使用面向对象编程有好处?

c - 在 C 循环中使用 asprintf 时发生内存泄漏

matlab - 在 Matlab 中连接二元运算符(如 "3++ 2")不会出错

perl - 给定/何时的哪些部分是实验性的?