gpt4 book ai didi

c++ - 在函数上获取段错误

转载 作者:太空宇宙 更新时间:2023-11-04 15:30:35 25 4
gpt4 key购买 nike

我有这个函数可以将月份从 3 个字符转换为 2 位数字的月份:

int Extract_Month(char *pDestMonth, char *pMonth)
{
char monthschar[12][4] = { "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" };
char monthsdigit[12][3] = { "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12" };
int i = 0;

char tmpStr[4] = "";
tmpStr[0] = (pMonth[0] >= 'a' && pMonth[0] <= 'z') ? ('a' + pMonth[0] - 'A') : pMonth[0];
tmpStr[1] = (pMonth[1] >= 'a' && pMonth[1] <= 'z') ? ('a' + pMonth[1] - 'A') : pMonth[1];
tmpStr[2] = (pMonth[2] >= 'a' && pMonth[2] <= 'z') ? ('a' + pMonth[2] - 'A') : pMonth[2];
tmpStr[3] = 0;

for (i = 0; i < 12; i++)
{
if (!strncmp(tmpStr, monthschar[i], 3))
{
StrMove((uchar *)pDestMonth, (uchar *)monthsdigit[i], 2);
return 0;
}
}
return -1;
}

我正在使用 gdb 运行它,但出现了段错误。有谁知道我在这里错过了什么?

我做了一些研究,发现段错误是由于内存处理不当造成的。

gdb 输出正好指向这个函数声明

这是调用函数的地方(简化代码): enter image description here

最佳答案

您正在以极其复杂的方式制作非常简单的东西..

既然你标记了它 ,您可以只使用 map 并像这样通过查找返回:

std::string Extract_Month_As_Digits(const std::string& month)
{
static std::map<std::string, std::string> monthToDigit = {{"JAN", "01"}};//omitted init.
auto found = monthToDigit.find(month);
return found != monthToDigit.end() ? *found : "";
}

如果你想在错误的输入/查找时抛出异常,你可以将其减少为return monthToDigit.at(month);

关于c++ - 在函数上获取段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54309693/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com