【问题标题】:why using const when passing arguments gives me a warning?为什么在传递参数时使用 const 会给我一个警告?
【发布时间】:2011-09-08 03:17:07
【问题描述】:

为什么这段代码给我一个警告说:从不兼容的指针类型传递“测试”的参数 1?我知道这是关于 char ** 之前的 const,但为什么呢?

void test(const int ** a)
{
}
int main()
{
    int a=0;
    int *b=&a;
    int **c=&b;
    test(c);
    return 0;
}

【问题讨论】:

标签: c function pointers constants


【解决方案1】:

您不能将int ** 分配给const int **,因为如果这样做,后一个指针将允许您为int * 变量提供const int 对象的地址:

const int myconst = 10;
int *intptr;
const int **x = &intptr;    /* This is the implicit conversion that isn't allowed */
*x = &myconst;              /* Allowed because both *x and &myconst are const int * ... */
/* ... but now intptr points at myconst, and you could try to modify myconst through it */

【讨论】:

    【解决方案2】:
    const int ** 
    

    是一个指向 const int 指针的指针,但你传递的是一个指向 int 指针的指针

    我想你可能想用int ** const 声明 test,它表示指针是 const 而不是值。

    注意:我认为这应该放在关于 C 中指针的每个问题中:cdecl.org 是提供人类可读表达式的一种非常好的方式

    【讨论】:

      【解决方案3】:

      这个问题的第二个答案可能会有所帮助:

      Why can't I convert 'char**' to a 'const char* const*' in C?

      不幸的是,接受的答案不是很好,也没有解释原因。

      【讨论】:

      • 答案显示顺序现在是随机的,所有者可以更改接受哪个答案,因此您可能需要澄清您参考的答案。另外我想说这个问题并不是特别相关:这个问题询问将int **转换为const int **的情况(注意缺少第二个const
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多