1、const *:表示指针指向的值不可变,但是指针可以重新赋新地址
-
#include <stdlib.h>
-
#include <stdio.h>
-
#include <string.h>
-
int main(void)
-
{
-
int test1 = 1;
-
int test2 = 2;
-
const int* p = &test1;//p指针存test1变量的地址
-
printf("%d ", *p);
-
p = &test2;//p指针存的地址发生改变,存test2变量的地址
-
printf("%d ", *p);
-
*p = 3; //企图修改p指针指向的值,由原来的2变成3
-
return 0;
-
}
输出结果:
验证上述说法“指针指向的值不可变”。
如果想修改p指针指向的值可以这样:
-
#include <stdlib.h>
-
#include <stdio.h>
-
#include <string.h>
-
int main(void)
-
{
-
int test1 = 1;
-
int test2 = 2;
-
const int* p = &test1;//p指针存test1变量的地址
-
printf("%d ", *p);
-
p = &test2;//p指针存的地址发生改变,存test2变量的地址
-
printf("%d ", *p);
-
test2 = 3;//注意是直接操作变量test2,而不是通过p指针去修改变量的值
-
printf("%d\n", *p);
-
return 0;
-
}
输出结果:
输出的是想要的值。
-
#include <stdlib.h>
-
#include <stdio.h>
-
#include <string.h>
-
int main(void)
-
{
-
int test1 = 1;
-
int test2 = 2;
-
const int* p = &test1;//p指针存test1变量的地址
-
printf("%d ", *p);
-
p = &test2;//p指针存的地址发生改变,存test2变量的地址
-
printf("%d\n", *p);
-
return 0;
-
}
输出结果:
验证上述说法“指针可以重新赋新地址”。
2、* const:表示指针表示的地址不可变,但是指针指向的值可变
-
#include <stdlib.h>
-
#include <stdio.h>
-
#include <string.h>
-
int main(void)
-
{
-
int test1 = 1;
-
int test2 = 2;
-
/*
-
int* const p;
-
p = &test1; //error: assignment of read-only variable ‘p’只能在声明的时候就给它赋初值(如下),否则还是会报错的
-
*/
-
int* const p = &test1;//p指针存test1变量的地址
-
printf("%d ", *p);
-
p = &test2;//企图修改p指针存的地址,由原来的test1变量的地址变成test2变量的地址
-
printf("%d ", *p);
-
return 0;
-
}
输出结果:
验证上述说法“指针表示的地址不可变”。
-
#include <stdlib.h>
-
#include <stdio.h>
-
#include <string.h>
-
int main(void)
-
{
-
int test1 = 1;
-
int test2 = 2;
-
/*
-
int* const p;
-
p = &test1; //error: assignment of read-only variable ‘p’只能在声明的时候就给它赋初值(如下),否则还是会报错的
-
*/
-
int* const p = &test1;//p指针存test1变量的地址
-
printf("%d ", *p);
-
*p = 3;//修改p指针指向的值,由原来的1变成3
-
printf("%d\n", *p);
-
return 0;
-
}
输出结果:
验证上述说法“指针指向的值可变”。
注意指针指向的是字符常量:
-
include <stdlib.h>
-
#include <stdio.h>
-
#include <string.h>
-
int main(void)
-
{
-
char* const p = "hello";//p指针存字符串常量"hello"的地址
-
printf("%s ", p);
-
p[0] = 'H';//企图通过指针p来修改的字符串常量的值,由原来"hello"的变成"Hello"
-
printf("%s\n", p);
-
return 0;
-
}
输出结果:
该程序的本意是“指针指向的值可变”,所以想修改字符串的值,但是出现段错误。
出现段错误的原因是:"hello"存放在常量区,在编译的时候就确定了,通过指针只可以访问字符串常量,而不可以改变该字符串常量。
可以这样操作修改字符串的值:
-
#include <stdlib.h>
-
#include <stdio.h>
-
#include <string.h>
-
int main(void)
-
{
-
char str[] = "hello";
-
char* const p = str;//p指针存字符串"hello"的地址
-
printf("%s ", p);
-
p[0] = 'H';//通过指针p来修改的字符串的值,由原来"hello"的变成"Hello"
-
printf("%s\n", p);
-
return 0;
-
}
输出结果:
由于char str[] = "hello",此时字符串"hello"存放在栈区,通过指针可读可修改。