为什么我们要写 sizeof(x) / sizeof(x[0]) 而不是在 C++ 中简单地编写 sizeof(x) 来确定数组的大小


sizeof() 运算符如何计算数组的大小

我尝试过的:

我编写了 sizeof(x) 来计算数组的大小,但没有得到预期的输出。

解决方案1

sizeof 返回参数使用的字节数:对于数组,即每个元素的大小乘以元素的数量。

尝试这个:

C
#include <stdio.h>

int main()
{
    int arr[10];
    printf("%lu:%lu\n", sizeof(arr), sizeof(arr[0]));

    return 0;
}

您将得到结果“40:4”:数组总共使用 40 个字节的内存,数组中的 10 个元素中的每一个使用 4 个字节。

解决方案2

一个小补充:你写的表达式,

C
sizeof( x ) / sizeof( x[0] )

用于计算数组中的项目数。 这与 _countof 宏在 VisualStudio C++ 中执行。

总结这三个表达式及其结果 int x[8] :

sizeof(x)               size in bytes of x             : 32
sizeof(x[0])            size in bytes of one item of x : 4
sizeof(x)/sizeof(x[0])  number of items in x           : 8

コメント

タイトルとURLをコピーしました