我正在尝试用 C 语言编写一个函数,该函数获取 int 作为参数并返回 char 数组(或字符串)。
const char * month(int x)
{
char result[40];
if(x<=31) strcpy(result,"can be a day of the month");
else strcpy(result,"cannot be a day of the month");
return result;
}
但是我的函数返回一个 int,而不是一个字符串。我读过人们可能遇到类似情况的帖子,但我无法理解指针类型函数如何工作以及如何使它们返回我想要的内容(我已经记录了一些关于指针的内容,并且我知道如何它们单独工作,但我从未尝试编写一段代码来为它们添加一些功能,例如使解决方案更有效或其他东西。)
最佳答案
const char * month(int x)
{
char result[40];
if(x<=31) strcpy(result,"can be a day of the month");
else strcpy(result,"cannot be a day of the month");
return result;
}
这没有道理。您返回一个指向数组的指针,但在函数返回后,该数组不再存在,因为结果
对于该函数来说是本地的。
对于C:
const char * month(int x)
{
if(x<=31) return "can be a day of the month";
return "cannot be a day of the month";
}
对于 C++:
std::string month(int x)
{
if(x<=31) return "can be a day of the month";
return "cannot be a day of the month";
}
关于c - C 中返回 int 值而不是字符串的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40075280/