1 常量与指针
1.1 常量与指针
常量与指针主要有如下几种形式:
const int* p;:p可变,p指向的内容不可变。int const* p;:p可变,p指向的内容不可变。int* const p;:p不可变,p指向的内容可变。const int* const p;:p和p指向的内容都不可变。
口诀: 左数右指。
当const出现在号左边时指针指向的数据为常量,当const出现在号后边时指针本身为常量。
#include <stdio.h>
int main()
{
int i = 0;
const int* p1 = &i;
int const* p2 = &i;
int* const p3 = &i;
const int* const p4 = &i;
*p1 = 1; // compile error
p1 = NULL; // ok
*p2 = 2; // compile error
p2 = NULL; // ok
*p3 = 3; // ok
p3 = NULL; // compile error
*p4 = 4; // compile error
p4 = NULL; // compile error
return 0;
}
参考资料:
本文深入解析了C语言中指针与常量的四种组合方式:const int *p, int const *p, int *const p, const int *const p。通过实例代码演示了每种情况下指针及所指向内容的可变性,帮助读者理解并掌握C语言中复杂指针类型的使用。
289

被折叠的 条评论
为什么被折叠?



