当我编译以下代码时,我得到了一些编译器警告。
#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_1
或ptr_3
修改值。
第20行有编译器警告,因为func_b()
不想修改*pptr
。 (即指针)。并且ptr_2
有可能改变指针。
但是,为什么第19行不会得到任何编译器警告? ptr_1
也可以更改指针。
声明int *const *pptr
声明pptr
是指向非常量int
的常量指针。
也就是说,该函数可以改变pptr
指向的(pptr = xxx
,相当无用),并且您可以更改int
的值(就像您在代码中所做的那样),但是您无法更改*pptr
(*pptr = yyy
无效)。
因为你用一个指向非常数int
的指针调用该函数,所以没关系。