//将4个字符串”Asia”,”America”,”Europe”,”Africa”按由小到大的顺序输出。要求用指向指针的指针完成。
#include<iostream>
using namespace std;
void sort(char **p);
int main()
{
int i;
char * *p, *pstr[4], str[4][20] = {"Asia", "America", "Europe", "Africa"};
p = pstr;
sort(p);
cout<<"字符串排序后为:"<<endl;
for(i = 0;i < 4; i ++)
{
cout<<pstr[i]<<endl;
}
return 0;
}
void sort(char * *p)
{
int i, j;
char *temp;
for(i = 0; i < 4; i ++)
{
for(j = i + 1; j < 4; j ++)
{
if(strcmp(*(p + i), *(p + j)) > 0)
{
temp = *(p + i);
*(p + i) = *(p + j);
*(p + j) = temp;
}
}
}
}
解决方案
15
#include<iostream>
using namespace std;
void sort(char **p);
int main()
{
int i;
char *pstr[4], str[4][20] = {"Asia", "America", "Europe", "Africa"};
for (int i=0; i<4; ++i)
{
pstr[i] = &str[i][0];
}
sort(&pstr[0]);
cout<<"字符串排序后为:"<<endl;
for(i = 0;i < 4; i ++)
{
cout<<pstr[i]<<endl;
}
return 0;
}
void sort(char * *p)
{
int i, j;
char *temp;
for(i = 0; i < 4; i ++)
{
for(j = i + 1; j < 4; j ++)
{
if(strcmp(*(p + i), *(p + j)) > 0)
{
temp = *(p + i);
*(p + i) = *(p + j);
*(p + j) = temp;
}
}
}
}
20
for(i = 0; i < 4-1; i ++)
“多一少一”问题占程序员常犯错误的10%以上!
避免“多一少一”问题的方法之一是将例如<10甚至<5的数代入程序片断,搬手指头心算验证一下程序到底应该写为
x、x-1、x+1中的哪个?
<、<=、==、>、>=中的哪个?
“多一少一”问题占程序员常犯错误的10%以上!
避免“多一少一”问题的方法之一是将例如<10甚至<5的数代入程序片断,搬手指头心算验证一下程序到底应该写为
x、x-1、x+1中的哪个?
<、<=、==、>、>=中的哪个?
10
上面没说到重点
刚帮你看了下,你的问题在于:
你的p指向的是pstr,而pstr你并没有为这个数组里的元素赋值
你的字符串是存在str里,你并没有让pstr数组中元素指向他