c - strtoul 给出意外的输出

标签 c strtol

我正在尝试使用 strtoul 函数,但如下所示,它返回一个意外的值(在开头添加 ff):

#include <stdio.h>
#include <string.h>
#include <limits.h>

main() {
    unsigned long temp ;
    char *err;
    temp = strtoul("3334444444",&err,10);
    if (temp > UINT_MAX) {
        printf("%lx %x %x\n",temp,3334444444,UINT_MAX);
    }else 
        printf("%lx %x\n",temp,3334444444);
}

$./a.out
ffffffffc6bf959c c6bf959c ffffffff 

上面的输出对应于 if 部分为 true,但我希望 else 部分在这里执行。谁能解释一下为什么 strtoul 会这样?为什么它返回 ffffffffc6bf959c 而不仅仅是 c6bf959c?如果我在上面的代码中使用 "333444444" (即仅少 1 个 4)而不是 "3334444444",那么我会得到正确的输出(即 13dff55c 13dff55c )对应于else部分。

注意:正如 melpomene 在下面的回复中指出的那样,应该包含 stdlib.h 头文件,这将解决问题。任何人都可以让我知道程序正在做什么,通过在编译时假设不正确的返回类型(在本例中为 int ),即使在知道之后也无法撤消(或至少在这种情况下它不会撤消)在链接期间正确的返回类型(在本例中为 unsigned long)?简而言之,我想知道由于未提供原型(prototype),c6bf959c 如何转换为 ffffffffc6bf959c。

最佳答案

使用 gcc 编译代码并启用警告会给出:

try.c:5:1: warning: return type defaults to ‘int’ [-Wimplicit-int]
 main() {
 ^~~~
try.c:5:1: warning: function declaration isn’t a prototype [-Wstrict-prototypes]
try.c: In function ‘main’:
try.c:8:12: warning: implicit declaration of function ‘strtoul’ [-Wimplicit-function-declaration]
     temp = strtoul("3334444444",&err,10);
            ^~~~~~~
try.c:8:5: warning: nested extern declaration of ‘strtoul’ [-Wnested-externs]
     temp = strtoul("3334444444",&err,10);
     ^~~~
try.c:10:22: warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 3 has type ‘long long int’ [-Wformat=]
         printf("%lx %x %x\n",temp,3334444444,UINT_MAX);
                      ^
try.c:12:22: warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 3 has type ‘long long int’ [-Wformat=]
         printf("%lx %x\n",temp,3334444444);
                      ^

主要问题是implicit declaration of function ‘strtoul’ ,表明该函数未声明(因此假定返回 int ),因为您忘记了 #include <stdlib.h> 。添加缺失的#include修复 temp 的值.

但是您还应该查看针对 printf 报告的警告并修复这些问题。

关于c - strtoul 给出意外的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38444756/

相关文章:

c++ - 在设计和构建嵌入式系统时考虑 Chaos Monkey

c - 套接字绑定(bind)失败(C 与 WinSock)

c++ - 如何做一个真正的strtoul?不会摄入实际的字符串

c - 使用 strtol() 解析文件行中的长值

使用 strtol() :\0' or '\n'? 从字符串转换为 int

在c中将字符串转换为int

c++ - 从字符串转换后如何返回十六进制值

c - C 中的非贪婪 fscanf 和缓冲区溢出检查

c - 为什么 stdlib.h 的 abs() 函数族返回有符号值?

php - 如何在 PHP 中优化 Dijkstra 代码?