指针作为数组元素指向字符串,指针元素按照指向的字符串由长到短的顺序存放。
程序
cpp
#define ARRAY_LEN 5
void bubble_a(char *dat,char n,char *p[]);
void swap1( char *xp, char *yp );
void swap2( char **xp, char **yp );
void main( )
{
char *myStrPtr[ARRAY_LEN]=
{
"If anything can go wrong,it will.",
"Nothing is foolproof.",
"",
"hello world.",
"Every solution breeds new problem."
};
char SLEN[ARRAY_LEN]={0};
int i,j;
for(i=0; i<ARRAY_LEN; i++)
for(j=0; *(myStrPtr[i]+j)!='\0'; j++)
SLEN[i] += 1;
bubble_a(SLEN, ARRAY_LEN, &myStrPtr[0]);
while(1);
}
void bubble_a(char *dat,char n,char *p[])
{
int i,next;
for(next=1; next<n; next++)
for(i=next-1; i>=0; i--)
if(dat[i+1]>dat[i]) //条件成立,调用交换函数swap1、swap2
{
swap1(&dat[i+1],&dat[i]);
swap2(&p[i+1],&p[i]);
}
}
void swap1( char *xp, char *yp )
{
char temp;
temp=*xp;
*xp=*yp;
*yp=temp;
}
/* 指针xp、yp指向的是地址, *xp是p[i+1],*yp是p[i] */
void swap2( char **xp, char **yp )
{
char *temp;
temp=*xp;
*xp=*yp;
*yp=temp;
}
执行程序后,数组myStrPtr的元素依次指向"Every solution breeds new problem.","If anything can go wrong,it will.", "Nothing is foolproof.","hello world."和空字符串。