【问题标题】:Call a c function with a const matrix argument using a const cast使用 const cast 调用带有 const 矩阵参数的 c 函数
【发布时间】:2015-09-30 11:54:51
【问题描述】:

我正在尝试使用 const 强制转换调用带有 const 矩阵参数的 c 函数,但找不到阻止 gcc 编译器抱怨的语法。如果删除了所有“const”强制转换,下面的代码编译时不会抱怨。该问题类似于C function const multidimensional-array argument strange warning,但没有提供完全令人满意的解决方案。在下面的代码中,如果第一次调用 g() 有效,那么第二次调用 g() 应该 也有效,因为它在语法上是相同的。但事实并非如此。首选 g() 的第二个版本,因为它不需要事先知道矩阵的类型。

/* file t.c */
void f(const int a[2]) {/*empty*/}
void g(const int b[2][2]) {/*empty*/}

int main()
{
    int a[2];
    int b[2][2];

    f((const int (*)) a);                   /* ok */
    f((const typeof(&a[0])) a);             /* ok */
    g((const int (*)[2]) b);                /* ok */
    g((const typeof(&b[0])) b);             /* compiler complains */
}

$ gcc -o t t.c
t.c: In function ‘main’:
t.c:13:2: warning: passing argument 1 of ‘g’ from incompatible pointer type [enabled by default]
  g((const typeof(&b[0])) b);  /* compiler complains */
  ^
t.c:3:10: note: expected ‘const int (*)[2]’ but argument is of type ‘int (*)[2]’
     void g(const int b[2][2]) {/*empty*/}

【问题讨论】:

  • const typeof(&b[0])int (* const)[2],而不是 const int (*)[2],即指针本身是 const,而不是元素。
  • 演员没有做任何有用的事情。您可以将函数调用为f(a)g(b)
  • 是的,只要调用函数 f(a) 和 g(b),一切正常。问题只是编译器在抱怨。我有一个大代码,它使用 const 参数调用库函数。 gcc 在汇编中乱扔不应该存在的投诉。

标签: c matrix casting constants


【解决方案1】:

声明头中的 const 表示函数不能改变参数的内容。它是给调用者(编译器)和程序员的信息。所以没有理由进行 const 类型转换然后调用该函数。完全是多余的。

【讨论】:

  • 如果不是因为编译器错误,那将是多余的。 ideone.com/Oow2hn
  • 我不知道,编译器就是这么做的。非常奇怪的行为。
【解决方案2】:

是的,无法使用非const 参数调用具有const 二维数组的函数确实是C 规范中的一个缺陷。

要在它周围移动,请记住

void g(const int b[2][2]) {/*empty*/}

改写为

void g(const int (*b)[2]) {/*empty*/}

因此,这向您展示了如何将其转换为 const int (*)[2],它是指向 2 个 double 的数组的指针。

g( (const int (*)[2])b );

【讨论】:

  • gcc 错误信息也有助于记住如何写类型:expected 'const int (*)[2]' but argument is of type 'int (*)[2]'
  • 这都是正确的。问题是 int (*)[2])b 应该与 typeof(&b[0]) 相同(我认为),但编译器不认为它们是相同的。
  • @ajsh,不应该和typeof(&b)一样,没有[0]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-19
  • 2012-02-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多