当数组是另一个函数的形式参数时,函数参数中类型定义的恒定大小数组的地址会导致指针类型不兼容

问题描述 投票:0回答:1

我已经阅读this thread并在其中搜索了更多信息,但是大多数人只是说“不要使用这种typedef。”这种做事方式对我很有吸引力,我也在尝试学习新事物,所以我要坚持下去。

我正在使用gcc版本9.2.1

这是我正在做的事情的最低再现性示例:

#define TABLE_SZ 10

typedef int vec_t[3];

typedef struct {
    vec_t table_one[TABLE_SZ];
} tables;

void foo(vec_t * foo_vec) {
  (*foo_vec)[0] = 0;
}

void bar (tables bar_table, vec_t bar_vec) {
  foo(&(bar_table.table_one[0]));
  foo(&bar_vec);
}


int main() {
  vec_t vector;
  foo(&vector);
}
/home/happy/CLionProjects/os_2019_p5/tests/test_array_typedef_ops.c: In function ‘bar’:
/home/happy/CLionProjects/os_2019_p5/tests/test_array_typedef_ops.c:18:7: warning: passing argument 1 of ‘foo’ from incompatible pointer type [-Wincompatible-pointer-types]
   18 |   foo(&bar_vec);
      |       ^~~~~~~~
      |       |
      |       int **
/home/happy/CLionProjects/os_2019_p5/tests/test_array_typedef_ops.c:12:18: note: expected ‘int (*)[3]’ but argument is of type ‘int **’
   12 | void foo(vec_t * foo_vec) {
      |          ~~~~~~~~^~~~~~~

我认为这与“指针衰减”有关,我想把bar_vec转换成int **吗?具体来说,当bar_vec为int **时,为什么&(bar_table.table_one [0])int(*)[3]的类型?

我显然不想抑制gcc中所有不兼容的指针类型警告。投射指针似乎有点麻烦。我想保留typedef。我不想将其隐藏在结构中。

是否有编译器标志或其他解决方案来告诉编译器按我期望的方式处理这种情况?有更多我应该注意的信息吗?

谢谢。

ps.s。堆栈溢出是否可以很好地打印出编译器输出?

我已经阅读了该线程并在其中搜索了更多信息,但是大多数人只是说“不要使用这种typedef。”这种做事方式对我很有吸引力,我也在尝试学习新的...

c arrays pointers typedef
1个回答
0
投票

void bar (tables bar_table, vec_t bar_vec)在很多方面都是不好的:

© www.soinside.com 2019 - 2024. All rights reserved.