You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

算术溢出警告:new double数组参数应选int还是int64?

关于new数组时参数类型与算术溢出警告的问题

问题背景

我编写了如下代码(其中nsections被定义为int类型):

pipe_def.p_atamb     = new double[pipe_def.nsections+1];

编译时收到如下算术溢出警告:

Arithmetic overflow: Using operator '+' on a 4 byte value and then
casting the result to a 8 byte value. Cast the value to the wider type
before calling operator '+' to avoid overflow (io.2).

特此咨询:在new double array(x)中,参数x应使用int还是int64类型?我原本认为应使用int。

解答

  • C++标准里,new[]的数组大小参数要求是std::size_t——这是一个无符号宽整数类型,通常和系统指针宽度一致(比如64位系统下等价于uint64_t)。你之前认为用int的想法存在误区。
  • 警告的根源是:nsections是4字节的int,当它接近int的最大值时,nsections+1会直接溢出32位范围,之后才被隐式转换为8字节的std::size_t,触发了溢出风险提示。
  • 解决警告的正确操作是先将nsections转换为宽类型再执行加法:
    pipe_def.p_atamb = new double[static_cast<std::size_t>(pipe_def.nsections) + 1];
    
  • 针对你的核心问题:参数x的最优类型是std::size_t,而非int或int64。int64是有符号类型,而数组大小不能为负,因此无符号的std::size_t更贴合场景;如果必须使用有符号类型,int64_t虽能避免溢出,但并非标准推荐的数组大小参数类型。

内容的提问来源于stack exchange,提问作者Adrian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 15:55:25