我收到以下代码的“分段错误(核心转储)”错误:
#include <iostream>
#include <cstring>
template <class T>
T maxn(T* elements, int n);
template <> const char* maxn <const char*>(const char* elements[], int num);
int main(){
using namespace std;
//Using template
int num[6] = {2, 3, 4, 5, 6, 22};
double num2[4] = {16.6, 10.5, 2.3, 1.1};
int larg = maxn(num, 6);
double larg2 = maxn(num2, 4);
cout << larg << endl << larg2 << endl;
//Using specialization
const char* pps[5] = {"Hello", "There", "I", "am", "me"};
const char* largest = maxn(pps, 5);
cout << largest << endl;
return 0;
}
//return largest element in an array of T of n elements
template <class T>
T maxn(T* elements, int n){
T largest = 0;
for (int i=0; i<n; i++)
largest = elements[i] > largest ? elements[i] : largest;
return largest;
}
//Returns address that points to the largest string
template <> const char* maxn <const char*>(const char* elements[], int num){
int longest = 0;
int i =0;
for (i=0; i<num; i++)
if (strlen(elements[i]) > strlen(elements[longest]))
longest = i;
return elements[i];
}
我收到“警告:不推荐使用从字符串常量到 'char* 的转换”错误,但后来我将一些char*数组和函数参数更改为const char*,我摆脱了它。现在代码编译,我得到以下输出:
22
16.6
分段错误(核心转储)
前两行是对的,但我不明白第三行会发生什么。请帮忙,谢谢。