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

为何sizeof(array)返回值是数组元素数的4倍?循环打印数组越界问题

问题原因及解决办法

你遇到的问题核心是对sizeof运算符的作用理解有误:

  • sizeof(A)返回的是整个数组占用的总字节数,而非数组的元素个数。你的int数组有8个元素,多数系统中int类型占4字节,所以总字节数是8*4=32,这就导致循环执行了32次。
  • 当循环下标i超过数组的最大合法下标(7,因为数组下标从0开始)后,你访问的是数组内存边界外的区域,这些区域的内容是未定义的随机值,所以会输出随机数。

解决方法

方法1:手动计算元素个数

用数组总字节数除以单个元素的字节数,得到准确的元素个数:

#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main()
{
        int A[] = {1, 2, 4, 8, 16, 32, 64, 128};
        int elementCount = sizeof(A) / sizeof(A[0]); // 计算元素个数:32/4=8
        for (int i = 0; i < elementCount; i++) {
                cout << A[i] << endl;
        }
}

方法2:使用C++11范围for循环(更简洁安全)

范围for循环会自动遍历数组的所有元素,无需手动控制下标和计数:

#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main()
{
        int A[] = {1, 2, 4, 8, 16, 32, 64, 128};
        for (int num : A) { // 自动遍历数组每个元素
                cout << num << endl;
        }
}

方法3:改用std::vector(现代C++推荐写法)

std::vector自带size()方法可以直接获取元素个数,同时具备更灵活的内存管理能力:

#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main()
{
        vector<int> A = {1, 2, 4, 8, 16, 32, 64, 128};
        for (int i = 0; i < A.size(); i++) {
                cout << A[i] << endl;
        }
        // 也可以配合范围for循环使用
        // for (int num : A) {
        //         cout << num << endl;
        // }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 06:30:08