1.指向数组的指针
#include<iostream>
using namespace std;
void sort(char (*p)[6]);
void main()
{ char str[10][6];
int i;
char (*p)[6] = str;
cout<<"input 6 strings:"<<endl;
for(i=0; i < 10; i++)
cin>>str[i];
sort(p);
cout<<"Now, the sequence is:"<<endl;
for(i=0; i < 10; i++)
cout<<str[i]<<endl;
}
void sort(char (*p)[6])
{ int i, j;
char temp[6], *q = temp;
for(i=0; i < 10; i++)
for(j=0; j < 10 - i; j++)
//由于p是指向一维数组的指针变量,指向一个包含6个元素的数组,务必弄清楚一下两点:
//1,p + j + 1表示指向下标为j+1的元素的首地址的地址,即&p[j+1]
//2,*(p + j + 1)相当于指向下标是j+1的数组的首地址,即p[j+1],“*”不可省略
//*(*(p + i + 1) + j)相当于str[i][j]的首地址,类似下文第2点“指向指针的指针”中下标的操作
//是一种间接访问
//以下这句相当于if(strcmp(p[j],p[j+1]) > 0)
if(strcmp(*(p + j), *(p + j + 1)) > 0)
{ strcpy(q, *(p+j)); //相当于strcpy(q,p[j]);
strcpy(*(p+j), *(p+j+1)); //相当于strcpy(p[j], p[j+1]);
strcpy(*(p+j+1), q); //相当于strcpy(p[j+1], q);
}
}
2.指向指针的指针
#include using namespace std;
void sort(char (*p)[6]);
void main()
{ char **p;
char * name[] = {"BASIC","FORTRAN","C++","PASCAL","COBOL"};
p = name;
cout<<*p<<endl;
cout<<*(*(p+1))<<endl;
cout<<*(*(p+1)+1)<<endl;
}
以上是练习《C++程序设计题解与上机指导》chapter 6.11解题方法2,以及对eg 6.8和eg6.16的总结。