[pg92@redhatB point]$ vim test_1.c /*Program test_1.c 常量指针: 指针存储的地址不能改变,但能改变指针指向的值.*/ #include<stdio.h> intmain(void) { int count=43; int sum=45; int *const pcount=&count; /*Defines a constant, means "pcount" read-only variable */ printf("n step1 count=%d",count); *pcount=143; pcount=∑ printf("n step2 count=%d",count); printf("nthe address of pcount is %p",pcount); printf("nthe value of pcount is %dn",*pcount); }
1.2 编译
1 2 3
[pg92@redhatB point]$ gcc -o test_1 test_1.c test_1.c: In function ‘main’: test_1.c:13: error: assignment of read-only variable ‘pcount’
备注:更改常量指针地址时,报错。
1.3 去掉 "pcount=∑" 行时,正常执行
1 2 3 4 5 6 7
[pg92@redhatB point]$ gcc -o test_1 test_1.c [pg92@redhatB point]$ ./test_1 step1 count=43 step2 count=143 the address of pcount is 0xbfc7b224 the value of pcount is 143
备注:从上面看出常量指针 pcount 存储的地址不能被修改,但能更改它指向的值。
二 指向常量的指针
指向常量的指针是指该指针指向的值不能通过指针改变,但能更改指针存储的地址。 声明如下:
1
constint *pcount=&count;
编写脚本测试: 2.1 指向常量的指针测试脚本。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
[pg92@redhatB point]$ vim test_2.c /*Program test_2.c 指向常量指针: 指针指向的值不能改变,但能改变指针地址.*/ #include<stdio.h> intmain(void) { int count=43; int sum=45; constint *pcount=&count; /*Defines a pointer to a constant,means "*pcount" is read-only. */ printf("n step1 *pcount=%d",*pcount); printf("n step1 The address of pcount is %p",pcount); pcount=∑ printf("n step2 *pcount=%d",*pcount); printf("n step2 The address of pcount is %pn",pcount); }
2.2 编译执行
1 2 3 4 5 6 7
[pg92@redhatB point]$ gcc -o test_2 test_2.c [pg92@redhatB point]$ ./test_2 step1 *pcount=43 step1 The address of pcount is 0xbfab4928 step2 *pcount=45 step2 The address of pcount is 0xbfab4924 [pg92@redhatB point]$