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

时间:2018-09-14 08:32:22

标签: c gcc

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

#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也可以更改指针。

0 个答案:

没有答案