【问题标题】:Different results when using atoi() for C in Mac OS X and Ubuntu在 Mac OS X 和 Ubuntu 中将 atoi() 用于 C 时的不同结果
【发布时间】:2012-09-05 15:55:03
【问题描述】:

这是我在 Mac OS X(10.8.1、64 位和 10.6.8、32 位)和 Ubuntu(10.04、32 位)上运行的代码:

printf("%d\n", atoi("2147483648"));
// returns -2147483648 in Mac OS X 10.8.1 and 10.6.8
// returns 2147483647 in Ubuntu

这是我在谷歌搜索后发现的:http://gynvael.coldwind.pl/?id=365

有什么原因导致不同系统的输出不同吗?

【问题讨论】:

  • IIRC 任何不能在其被转换为的类型中表示的值都具有由实现定义的值。在你的情况下 libc 只返回 INT_MAX 而在 Mac OS 中你会得到一个溢出
  • Ubuntu 32 位还是 64 位?

标签: c glibc atoi


【解决方案1】:

这并不奇怪,因为行为is not specified按标准:

当转换后的值超出 int 可表示的值范围时会发生什么,没有标准规范。

strtol 函数在返回中为您提供更多信息,因为当值不适合 long int 时,它会将 errno 设置为 ERANGE

【讨论】:

    猜你喜欢
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 2016-07-06
    • 1970-01-01
    • 2013-06-28
    • 1970-01-01
    • 2012-01-08
    • 1970-01-01
    相关资源
    最近更新 更多