关于const字符串数组存储一个奇怪的现象

mcmay mcmay 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
以下代码的作用是返回数组中最大值(如果是字符串数组则返回数组中最长的那个字符串,如果有几个等长字符串最长,则返回其中第一个的地址)
// ex6, ch 8
#include <iostream>
#include <cstring>

template <typename T>
T ret_max(T [], int);

template <> char * ret_max(char *[], int);

int main()
{
using namespace std;
int ar_int[6] = {3, 7, 2, 5, 6, 4};
double ar_doub[4] = {2.1, 3.4, 1.8, 4.2};
char * str[5] = {
"I really can't understand you.",
"You're my dearest baby.",
"How much do you love me?",
"I really can't understand you.",
"I really can't understand you."
};
char * s;

cout << "Max of the six integers: " << ret_max(ar_int, 6) << endl;;
cout << "Max of the four integers: " << ret_max(ar_doub, 4) << endl;
cout << "The five strings and their addresses:" << endl;
for (int i = 0; i < 5; i++)
{
cout << str[i] << endl;
cout << (unsigned)str[i] << endl;
}
cout << "The largest of the five and its address:" << endl;
s = ret_max(str, 5);
cout << s << endl;
cout << (unsigned)s << endl; // 用unsigned打印指针内容,请还有其他打印法可以显示0x进制的模式吗?

return 0;
}

template <typename T>
T ret_max(T ar[], int n)
{
T max = ar[0];
for(int i = 0; i < n; i++)
if(max < ar[i])
max = ar[i];
return max;
}

template <> char * ret_max(char * str[], int n)
{
int i, max = 0;

for(i = 0; i < n; i++)
if(strlen(str[max]) < strlen(str[i]))
max = i;

return str[max];
}


运行结果:
Max of the six integers: 7
Max of the four integers: 4.2
The five strings and their addresses:
I really can't understand you.
4214892 // 这些长度一致的数组,竟然地址一样!
You're my dearest baby.
4214923
How much do you love me?
4214947
I really can't understand you.
4214892 // 同上
I really can't understand you.
4214892 // 同上
The largest of the five and its address:
I really can't understand you.
4214892
...全文

相关推荐

评论 5
收藏 已收藏
分享
返回顶部
mcmay
C++ 语言 65,214 成员 250,514 内容