传递const变量时不兼容的指针类型

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

当我编译以下代码时,我得到了一些编译器警告。

#include <stdio.h>
int global = 10;
void func_a(const int **pptr) {
    *pptr = &global;
}
void func_b(int *const *pptr) {
    **pptr = 20;
}
int main()
{
    int local = 30;
    int *ptr_1 = &local;
    const int *ptr_2 = &local;
    int* const ptr_3 = &local;
    func_a(&ptr_1); /* line 15 : compile warning */
    func_a(&ptr_2); /* line 16 : compile okay */
    func_a(&ptr_3); /* line 17 : compile warning */

    func_b(&ptr_1); /* line 19: compile okay? */
    func_b(&ptr_2); /* line 20: compile warning */
    func_b(&ptr_3); /* line 21: compile okay */

    return 0;
}

警告:

a.c:15:12: warning: passing argument 1 of 'func_a' from incompatible pointer type [-Wincompatible-pointer-types]
a.c:17:12: warning: passing argument 1 of 'func_a' from incompatible pointer type [-Wincompatible-pointer-types]
a.c:20:12: warning: passing argument 1 of 'func_b' from incompatible pointer type [-Wincompatible-pointer-types]

根据我的理解,第15行和第17行有编译器警告,因为func_a()不想修改**pptr。 (即local的价值)。编译器发现可以通过指针ptr_1ptr_3修改值。

第20行有编译器警告,因为func_b()不想修改*pptr。 (即指针)。并且ptr_2有可能改变指针。

但是,为什么第19行不会得到任何编译器警告? ptr_1也可以更改指针。

c gcc
1个回答
1
投票

声明int *const *pptr声明pptr是指向非常量int的常量指针。

也就是说,该函数可以改变pptr指向的(pptr = xxx,相当无用),并且您可以更改int的值(就像您在代码中所做的那样),但是您无法更改*pptr*pptr = yyy无效)。

因为你用一个指向非常数int的指针调用该函数,所以没关系。

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