c - C 中返回 int 值而不是字符串的函数

标签 c pointers char

我正在尝试用 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/

相关文章:

c - SysV 信号量是否在文件系统中表示?

c - 多态性(在 C 中)

c - 将指针传递给嵌套函数

c - = 的操作数具有非法类型

c - 动态二维字符数组分配无法正常工作

c - 从 C 中的 unsigned int 末尾获取 'n' 二进制位?位掩码?

c - 'ptr = &array[index]' 和 '*ptr = array[index]' 和有什么区别?

c++ - 继承和指向指针 : why doesn't it work and how do I get around it? 的指针

java - JNA 通过引用在 C 结构中使用多个 void 指针

c++ - 如何将整数附加到字符串?