私はstrtoul
機能を使用しようとしていますが、それ以下のように予期しない値(付加初めでのFFの)戻っている:strtoulを与える予期しない出力
#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
がこのように振る舞っている理由を説明できますか?なぜc6bf959c
ではなくffffffffc6bf959c
が返されますか?上記のコードで"3334444444"
ではなく"333444444"
(つまりわずか4分の1)を使用すると、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.
あなたはstrtoulの代わりにstrtoullを試しましたか? – bruceg
私はこのコードで期待される動作を得ています。あなたの環境は何ですか? –
'ULONG_MAX'は、32ビットシステムでは' UINT_MAX'と同じサイズです。 bruegが言ったように、 'strtoull'は良いでしょう。 – yellowantphil