C++指针——(2)指针的进阶知识

来源:互联网 发布:python os 编辑:程序博客网 时间:2024/06/05 03:20

1.typedef定义同义类型
利用typedef关键字定义同义类型


语法如下:

typedef existingType newType;

例如:

typedef int integer;integer value = 40;

等价于

int value = 40;

同样的,对于指针变量来讲,我们有

typedef int* intPoint;intPoint p1,p2;//可以避免int* 同时定义两个变量出现的问题

2.数据常量和指针常量

double radius = 5;double* const p = &radius;//指针常量

指针常量指的是指针定义赋值后不能再赋予新的地址。
但指针指向的数据值可以改变。
例如:

*p =10;//正确p=&newRadius;//错误

[说明]

const double* const pValue = &radius;

其中第一个const是常量数据,第二个是常量指针。


给出更多的代码例子

double radius = 5;double*const p = &radius;double newRadius = 6;*p = 7;// correctp = &newRadius; //wrongconst double* p1= &radius;*p=7;//wrongp1 = &newRadius;//correctconst double* const p2 =&radius;*p2 = 7;//wrongp2 = &newRadius;//wrong

3.数组和指针的关系

一个数组变量实质是一个指针。我们假设已经声明了一个数组

int list[6] = {11,12,13,14,15,16};

下面的语句可以用来打印数组的首地址:

cout << "The starting address of the array is " << list << endl;
数组下标 list[0] list [1] list [2] list [3] list[4] list[5] 数组元素 11 12 13 14 15 16 内存地址 1000 1004 1008 1012 1016 1020

[备注]:地址值的增加减少与sizeof(type)有关


给出一个指针访问数组元素的例子

#include<iostream>using namespace std;int main(){    int list[6] = {11,12,13,14,15,16};    for(int i = 0; i < 6; i++)        cout << "address: " << (list + i) << " value: "              <<*(list + i) << " "<< " value: "              <<list[i] <<endl;    return 0;}

给出很多的例子

#include<iostream>using namespace std;int main(){    int list[6] = { 11,12,13,14,15,16 };    int* p = list;    for (int i = 0; i < 6; i++)        cout << "address: " << (list + i) <<         " value: "<< *(list + i) << " " <<        " value: "<< list[i] << " " <<        " value: "<<*(p + i )<< " " <<         " value: " << p[i] << endl;    return 0;}

运行结果
这里写图片描述


[说明]
1)以下两组代码等价

int* p = list;
int* p = &list[0];

2)数组与指针在访问元素时等价,而数组声明后无法改变地址

int list1[10],list2[10];list1 = list2;//wrong

从这个意义上来讲,在C++中数组名实质上是一个常量指针

3)C字符串也可以通过指针来访问

char city[8] = "NanJing";

等价于

char* pCity = "NanJing";

每个声明都是创建了

1 2 3 4 5 6 7 8 N a n J i n g \0

也可以利用数组和指针语法来访问city或者pCity

cout << city[1] <<endl;cout << *(city + 1) <<endl;cout << pCity[1] <<endl;cout << *(pCity + 1) <<endl;

0 0
原创粉丝点击