返回列表 回复 发帖

vc++ 请教

  查找最大字符串数组,编译连接没有错,为何最后的cout没有输出?
#include <iostream.h>
#include <string.h>
#include <stdio.h>

char *max (char *p[],int n)  //定义查找字符串数组中最大字符串函数
{


for(int i = 0;i < n;i++)
if(strcmp(p[0],p)<0)   //假定p[0]最大,查找最大值
strcpy(p[0],p);
return p[0];
}
void main()
{


char *c[3]={"ao","ss","da"};


cout<<c[0]<<endl;
cout<<c[1]<<endl;
cout<<c[2]<<endl;
cout<<max(c,3)<<endl;

}
这种带[ i ]的
看的眼疼
http://blog.csdn.net/thisisll/ http://spaces.msn.com/thisisll/
函数这样写就好了
char *max (char *p[],int n) //定义查找字符串数组中最大字符串函数
{
   char* pTmp = p[0];
   for(int j = 0;j < n;j++)
   {
      if(strcmp(pTmp,p[j])<0)  //假定p[0]最大,查找最大值
      {
         pTmp = p[j];
      }
   }
   return pTmp;
}
为了避免眼疼  偶用[j]  HOHO
二楼的,你咋能反回局部指针呢?
#include <iostream.h>
#include <string.h>
char *max(char a[][10])
{
    char *g=a[0];
   
    for(int i=1;i<3;i++)
        if(strcmp(g,a)<0) strcpy(g,a);
    return g;
}

void main()
{
    char b[][10]={"zfdsfd","zsfjsd","sdfsd"};
    cout<<"the max is:"<<max(b)<<endl;
}
下面是引用Memory于2005-09-23 21:34发表的:
二楼的,你咋能反回局部指针呢?
不是局部指针  返回值指向的是调用函数使用的内存
二楼的正确
楼主的程序最简单的该法:
char *max (char *p[],int n) //定义查找字符串数组中最大字符串函数
{


for(int i = 0;i < n;i++)
{
    if(strcmp(p[0],p)<0)  //假定p[0]最大,查找最大值
        //strcpy(p[0],p);
        p[0]=p;
}
return p[0];
}
只需将strcpy函数改为p[0]=p即可
发错了,因该是:
char *max (char *p[],int n) //定义查找字符串数组中最大字符串函数
{


for(int i = 0;i < n;i++)
{
    if(strcmp(p[0],p)<0)  //假定p[0]最大,查找最大值
        //strcpy(p[0],p);
        p[0]=p;
}
return p[0];
}
返回列表