“警告:返回从指针生成整数而不进行强制转换”是什么意思? 意思是C语言?

发布于 2024-07-18 10:05:30 字数 419 浏览 12 评论 0原文

我正在用 C 编写一个简单的函数,其目的是获取一个 6 位数字,计算出前 3 位,并基于此返回“r”、“w”或“o”。

但是,当我编译时,我收到此警告:“返回从指针生成整数而不进行强制转换”。 然后,当我运行该程序时,我发现该函数返回一个奇怪的字符,它绝对不是我所追求的三个字符之一。

这里发生了什么? 提前致谢。

这是我的功能:

char
readorwrite(int opcode)
{
    if (opcode >> 3 == 4) {
        return "r";
    } else if (opcode >> 3 == 5) {
        return "w";
    } else {
        return "o";
    }
}

I'm writing a simple function in C whose purpose is to take a 6 bit number, work out the first 3 bits, and based on that, return a "r", "w" or "o".

However, when I compile I get this warning: 'return makes integer from pointer without a cast'. Then, when I run the program, I find that the function is returning a weird character that definitely isn't one of the three I'm after.

What is going on here? Thanks in advance.

Here's my function:

char
readorwrite(int opcode)
{
    if (opcode >> 3 == 4) {
        return "r";
    } else if (opcode >> 3 == 5) {
        return "w";
    } else {
        return "o";
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

深居我梦 2024-07-25 10:05:30

问题是“r”、“w”和“o”是字符串常量,这意味着它们的实际类型是char[]或char*。 这意味着您的函数实际上返回 s 指向以零结尾的字符串的指针。 对于单个字符,您应该使用“r”、“w”和“o”。

The problem is that "r", "w" and "o" are string constants, which means that their actual type is char[] or char*. That means your function is actually returning s pointer to a zero-terminated string. For single characters, you should use 'r', 'w', and 'o' instead.

往事随风而去 2024-07-25 10:05:30

您返回一个 const char *,即指向内存中存储字符串“o”的位置的指针,而您应该返回一个 char 'o'

You return a const char *, ie a pointer to a location in memory where the string "o" is stored when you should be returning a char 'o'

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文