1·非常量数据的非常量指针
定义:int *ptr;
举例说明:
#include <stdio.h>
//非常量数据的非常量指针指向的内存地址和存储的内容都可以改变!
int main()
{
int a = 100;
int b = 200;
int *ptr = &a ;
*ptr = b; //合法
ptr = &b; //合法
return 0;
}
2·常量数据的非常量指针
定义:const int *ptr;
举例说明:
#include <stdio.h>
//常量数据的非常量指针指向的内存地址可以改变但是存储的内容不可以改变!
int main()
{
const int a = 100;//定义一个常量数据
int b = 200;
const int *ptr = &a ;//指向一个常量数据的非常量指针
//这时候表示指针指向的内存地址可以改变,但是地址里面储存的内容不能改变!
ptr = &b; //合法
*ptr = b; //非法!
//VC++6.0编译结果:error C2166: l-value specifies const object
//把光标移到编译这条编译信息里,按F1,可以看看MSDN关于这条编译错误的定义
return 0;
}
3·非常量数据的常量指针
定义:int * const ptr;
举例说明:
#include <stdio.h>
//非常量数据的常量指针指向的内存地址不可以改变但是存储的内容可以!
int main()
{
int a = 100;
int b = 200;
int * const ptr = &a;//这里一旦指向一个固定的地址以后就不可以再改变了
//但是地址里面存放的内容依然可以改变
ptr = &b; //非法!
*ptr = b; //合法
return 0;
}
4·常量数据的常量指针
定义:const int * const ptr;
举例说明:
#include <stdio.h>
//常量数据的常量指针指向的内存地址和存储的内容都不可改变!
int main()
{
const int a = 100;
int b = 200;
const int * const ptr = &a;
ptr = &b; //非法!
*ptr = b; //非法!
return 0;
}
以上代码均在VC++6.0上测试过。
注意:可能有些编译器不支持const!