c++ -数组的计数与声明的大小无关

C++ - the count of the array is irrelevant to the declared size

本文关键字:声明 数组 c++      更新时间:2023-10-16

我编写了以下代码块。但是sizeof()返回的数组的大小是无关的。我有一个包含6个元素的数组,而sizeof()返回24作为数组的大小。

代码如下:

#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
    int arr[6] = { 0, 5, 8, 32, 100, 41 };
    int arrSize = sizeof(arr);
    int i = 0;
    cout << "This is the Size of Array: " << arrSize << endl;
    /*
    for (i = 0; i < arrSize; ++i)
    {
      cout << arr[i] << endl;
    }   */
    return 0;
}

下面是输出:

This is the Size of Array: 24

你应该这样做

int size = sizeof(arr)/sizeof(arr[0]);

这将查找数组的总大小。这里是6 * 4 = 24,然后除以单个元素的大小,因此24/4 = 6

sizeof给出了数据的大小,以字节为单位

6 * 4字节整数= 24 字节