求指出哪里错了。将4个字符串”Asia”,”America”,”Europe”,”Africa”按由小到大的顺

C++语言 码拜 8年前 (2016-04-20) 888次浏览
//将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

引用:
Quote: 引用:

你的这一部分:
for(i = 0; i < 4; i ++)
{
for(j = i + 1; j < 4; j ++)
第一层循环中,i可以取到3,于是第二层的j可以取到4,而数组索引有效值只是0-3

当i取到3的时候,j取到4,但此时循环已经终止了

上面没说到重点
刚帮你看了下,你的问题在于:
你的p指向的是pstr,而pstr你并没有为这个数组里的元素赋值
你的字符串是存在str里,你并没有让pstr数组中元素指向他


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明求指出哪里错了。将4个字符串”Asia”,”America”,”Europe”,”Africa”按由小到大的顺
喜欢 (0)
[1034331897@qq.com]
分享 (0)