怎么样返回字符串的地址

C++语言 码拜 7年前 (2017-04-19) 1629次浏览
题目是primer plus的一道题,先看看本人写的代码把
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
template<class T>T max5(T a[],int n);
template<>char* max5(char* ch[],int n);
int main()
{
int num1[4]={1,2,3,4};
double num2[6]={1.2,1.3,1.4,1.5,1.6,1.7};
char* str[3]={“China”,”Britain”,”England”};
int max1=max5(num1,4);
double max2=max5(num2,6);
char* ps=new char*;
ps=max5(str,3);
cout<<max1<<” “<<max2;
return 0;
}
template<class T>T max5(T a[],int n)
{
T max=a[0];
for(int i=1;i<n;i++)
max=a[i]>max ? a[i]:max;
return max;
}
template<>char* max5(char* ch[],int n)
{
int num[n];
for(int i=0;i<n;i++)
num[i]=strlen(ch[i]);
int max=0;
for(int i=1;i<n;i++)
max=num[i]>num[max] ? i:max;
return ch;
}
对于第二个函数,题目要求返回字符最多的字符串的地址。虽然ch是一个地址,但只是字符串第一个元素的地址,本人想返回整个字符串的地址,也就是说:
在主函数中,本人定义一个
char *ps[3]
那么本人该怎么样设计函数头使得这个初始化的字符串指针可以:
ps=max5(str,3)
呢?
解决方案

80

C/C++中函数不能返回数组类型,数组作为参数也会退化为指针
也就是说你,max5中的参数ch实际是char**类型
你max5把返回值改成char**
调用时:
char **ps;
ps=max5(str,3)

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明怎么样返回字符串的地址
喜欢 (0)
[1034331897@qq.com]
分享 (0)