# 38-c++-指针小结

xiaoxiao2021-03-01  4

4.8 指针、数组和指针算术

//addpntrs.cpp——pointer addition #include<iostream> int main() { using namespace std; double wages[3] = {10000.0 , 20000.0 , 30000.0}; short stacks[3] = {3,2,1}; double * pw = wages; short * ps = &stacks[0]; cout<<"pw = "<<pw<<" , *pw = "<<*pw<<endl; pw=pw+1; cout<<"and 1 to the pw pointer\n"; cout<<"pw = "<<pw<<" , *pw = "<<*pw<<endl<<endl; cout<<"ps = "<<ps<<" , *ps = "<<*ps<<endl; ps=ps+1; cout<<"and 1 to the ps pointer\n"; cout<<"ps = "<<ps<<" , *ps = "<<*ps<<endl<<endl; cout<<"access two elements with array notation\n"; cout<<"stacks[0] = "<<stacks[0] <<", stacks[1] = "<<stacks[1]<<endl; cout<<"access two elements with array notation\n"; cout<<"access two elements with pointer notation\n"; cout<<"*stacks = "<<*stacks <<", *(stacks+1) = "<<*(stacks+1)<<endl; cout<<sizeof(wages)<<" = size of wages array\n"; cout<<sizeof(pw)<<" = size of pw pointer\n"; return 0; }

4.8.1  程序说明

double * pw = wages;

wages = &wages[0] = address of first element of array

arrayname[i] becomes * (arrayname + i);

pointername [i] becomes * (pointername + i);

pointername = pointername + 1;

arrayname = arrayname + 1;

24 = size of wages array << displaying sizeof wages

4 = size of pw pointer << displaying sizeof pw

short tell [10];

cout << tell <<endl;

cout << &tell << endl;

short  (*pas) [20] = &tell;

4.8.2 指针小结

1. 声明指针

typeName * pointerName;

double * pn;

char *pc;

2. 给指针赋值

double * pn ;

double * pa ;

char * pc ;

double bubble = 3.2 ;

pn = &bubble ;

pc = new char;

pa = new double [30] ;

3. 对指针解除引用

cout<<*pn;

*pc = S;

4.区分指针和指针所指向的值

int * pt = new int ;

* pt = 5;

5.数组名

int tacos[10];

6.指针算术

C++允许将指针和整数相加。加1的结果等于原来的地址值加上指向的对象占用的总字节数。还可以将一个指针减去另一个指针，获得两个指针的差。后一种运算将得到一个整数，仅当两个指针指向同一个数组（也可以指向超出结尾的一个位置）时，这种运算才有意义；这将得到两个元素的间隔。

int tacos [10] = {5,2,8,4,1,2,2,4,6,8};

int * pt = tacos ;

pt = pt + 1;

int *pe = &tacos[9];

pe = pe - 1;

int diff = pe - pt ;

7. 数组的动态联编和静态联编

int tacos[10];

int size;

cin>>size;

int * pz = new int [size];

...

delete [] pz;

8. 数组表示法和指针表示法

tacos[0] means * tacos means the value at address tacos

tacos[3] means * (tacos + 3) means the value at address tacos + 3

int * pt = new int [10];

*pt = 5;

pt[0] = 6;

pt[9] = 44;

int coats[10];

*(coats + 4) = 12;