我正在尝试使用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"(即少四分之一),而不是"3334444444",那么我会得到与13dff55c 13dff55c部分相对应的正确输出(即else)。

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.

最佳答案

在启用了警告的情况下使用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/

10-14 19:33