您的位置:首页 > 其它

const与指针结合的三种情况

2015-10-29 09:21 211 查看
/*
* ppp.c
*
*  Created on: 2015年10月29日
*      Author: xn666
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//一、没有任何修饰的指针,无论是指针本身还是指针指向的内存空间,都可以修改
void func01(){
int * p = NULL;
int a = 20;
int b = 40;
p = &a;
printf("%p\n",p); //显示指针本身的值
p = &b;
printf("%p\n",p); //显示修改指针后的本身值
*p = 6;
printf("%d\n",*p); //显示修改指针指向后的值
}

//二、使用const修饰的指针有三种分别是:
//1.const int *p         //不能修改指针指向的内存空间中的值
//2.int * const p         //不能修改指针本身指向,但是可以修改指向内存空间的值
//3.const int * const p  //无论是指向的内存空间还是指针本身的值,都不可以修改
void func02(){
int a = 3;
int b = 4;

//1.const int *p
const int *p = &a;
//*p = 5; //编译会提示,这是错误的语法
printf("const int *p =  %d\n",*p);
p = &b;
printf("const int *p =  %d\n",*p);

//2.int * const p
int * const t = &a;
//t = &b; //编译会提示,这是错误的语法
printf("const int *t =  %d\n",*t);
*t = 7;
printf("const int *t =  %d\n",*t);

//3.const int * const p
const int * const s = &a;
//s = &b;  //编译会提示,这两种情况都违法的
//*s = 8;
printf("const int *s =  %d\n",*s);

}
int main(){

//func01();
func02();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: