1. 作用说明:
在指针前加 const 的用途为:不可改变指针指向的内存的值,即将该指向指向的内存中的变量置为只读(read-only) 变量。
但是,可以给 const 的指针赋值,即将具有 const 属性的指针指向别的内存地址,此时,const 属性不变。
2. 示例代码
示例 1:
#include <stdio.h> int main(void) { int a = 10, b = 15; const int *p = &a; printf("*p = %d\n", *p); p = &b; printf("*p = %d\n", *p); return 0; }
运行结果:
示例 2:
#include <stdio.h>
int main(void)
{
int a = 10, b = 15;
const int *p = &a;
printf("*p = %d\n", *p);
p = &b;
printf("*p = %d\n", *p);
*p = 14;
return 0;
}
编译结果:
示例 3:
#include <stdio.h>
int main(void)
{
const int a = 10;
const int *p = &a;
printf("*p = %d\n", *p);
return 0;
}
运行结果:
示例 4:
#include <stdio.h>
int main(void)
{
const int a = 10;
int *p = &a;
printf("*p = %d\n", *p);
return 0;
}
编译结果:
示例 5(此时 const 限制 Test * 类型的指针变量指向的值,即限制指针去修改值):
#include <stdio.h>
#include <string.h>
typedef struct {
int a;
int b;
} Test;
int main(void)
{
Test test = { 1, 2 };
const Test *p = &test;
p->a = 10;
printf("test.a = %d\n", test.a);
return 0;
}
编译结果:
示例 6(此时 const 仅仅修饰 T 类型变量,即该变量不可被改变(参考示例 7),该指针指向的值可被修改):
#include <stdio.h>
#include <string.h>
typedef struct {
int a;
int b;
} Test;
typedef Test *T;
int main(void)
{
Test test = { 1, 2 };
const T p = &test;
p->a = 10;
printf("test.a = %d\n", test.a);
return 0;
}
运行结果:
示例 7:
#include <stdio.h>
#include <string.h>
typedef struct {
int a;
int b;
} Test;
typedef Test *T;
int main(void)
{
Test test = { 1, 2 };
Test test2 = { 3, 4 };
const T p = &test;
p = &test2;
p->a = 10;
printf("test.a = %d\n", test.a);
return 0;
}
编译结果: