如何返回字符串的地址?

LBWANDWC 2016-10-13 06:14:45
题目是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)
呢?
...全文
343 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
AlbertS 2016-10-13
  • 打赏
  • 举报
回复
引用 1 楼 paschen 的回复:
C/C++中函数不能返回数组类型,数组作为参数也会退化为指针 也就是说你,max5中的参数ch实际是char**类型 你max5把返回值改成char** 调用时: char **ps; ps=max5(str,3)
赞她就是这么有道理
paschen 版主 2016-10-13
  • 打赏
  • 举报
回复
C/C++中函数不能返回数组类型,数组作为参数也会退化为指针 也就是说你,max5中的参数ch实际是char**类型 你max5把返回值改成char** 调用时: char **ps; ps=max5(str,3)

64,676

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧