【发布时间】:2025-11-24 21:55:02
【问题描述】:
我正在尝试使用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 部分为真,尽管我希望else 部分在这里执行。谁能解释为什么strtoul 会这样?为什么它返回ffffffffc6bf959c 而不仅仅是c6bf959c?如果我在上面的代码中使用"333444444"(即少一个4)而不是"3334444444",那么我得到与else部分对应的正确输出(即13dff55c 13dff55c)。
Note : As pointed by melpomene in his reply below, stdlib.h header file should have been included and that will resolve the issue. Can anyone please let me know what is being done by the program by assuming the incorrect return type (int in this case) during compile time which can't be undone (or atleast it is not getting undone in this case) even after knowing the correct return type (unsigned long in this case) during link time ? In short, i want to know how c6bf959c is getting converted to ffffffffc6bf959c because of prototype not provided.
【问题讨论】:
-
你试过用strtoull代替strtoul吗?
-
我得到了您对这段代码的预期行为。你的环境是什么?
-
ULONG_MAX与 32 位系统上的UINT_MAX大小相同。strtoull会更好,就像 brueg 说的那样。 -
无符号长整数的最大值为 4294967295,因此您的 if 条件将为假(计算为零)。这可能取决于您的编译器和平台,我在 Windows 上使用了 Oepn Watcom。当传递一个大于 4294967295 的值时,我得到 FFFFFFFF。
-
3334444444可能是unsigned、unsigned long或者甚至可能是long(或其他类型)。所以"%x"可能是个问题。推荐printf("%lx\n",3334444444UL);,避免不确定。