C++ sizeof(arr) / sizeof(arr[0]) 如何工作?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33523585/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 14:17:19  来源:igfitidea点击:

How do sizeof(arr) / sizeof(arr[0]) work?

c++sizeof

提问by Felix Willis

When looking for a size of an array in a for loop I've seen people write

在 for 循环中寻找数组的大小时,我见过人们写

int arr[10];
for(int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++){}

How is sizeof(arr) / sizeof(arr[0])the length of the array? How does it technically work?

sizeof(arr) / sizeof(arr[0])数组的长度如何?它在技术上是如何工作的?

回答by rozina

If you have an arraythen sizeof(array)returns the number of bytes the array occupies. Since each element can take more than 1 byte of space, you have to divide the result with the size of one element (sizeof(array[0])). This gives you number of elements in the array.

如果有,arraysizeof(array)返回数组占用的字节数。由于每个元素可能占用超过 1 个字节的空间,因此您必须将结果除以一个元素的大小 ( sizeof(array[0]))。这为您提供了数组中的元素数。

Example:

例子:

std::uint32_t array[10];

auto sizeOfInt = sizeof(std::uint32_t); // 4
auto numOfBytes = sizeof(array); // 10*sizeOfInt = 40
auto sizeOfElement = sizeof(array[0]); // sizeOfInt = 4
auto numOfElements = sizeof(array) / sizeof(array[0]); // numOfBytes / sizeOfElement = 40 / 4 = 10

LIVE EXAMPLE

现场示例

Note that if you pass an array to a function, the above won't work since the array decays to a pointer and sizeof(array)returns the size of the pointer.

请注意,如果将数组传递给函数,则上述方法将不起作用,因为数组会衰减为指针并sizeof(array)返回指针的大小。

std::size_t function(std::uint32_t a[]) // same for void function(std::uint32_t a[10])
{
    return sizeof(a); // sizeof(std::uint32_t*)!
}

std::uint32_t array[10];
auto sizeOfArray = function(array); // array decays to a pointer inside function()

LIVE EXAMPLE #2

现场示例#2

回答by Vlad from Moscow

As it is described in the C++ Standard (5.3.3 Sizeof)

正如 C++ 标准 (5.3.3 Sizeof) 中所述

1 The sizeof operator yields the number of bytes in the object representation of its operand. The operand is either an expression, which is an unevaluated operand (Clause 5), or a parenthesized type-id.

1 sizeof 运算符产生其操作数的对象表示中的字节数。操作数要么是一个表达式,它是一个未计算的操作数(第 5 条),要么是一个带括号的类型 ID。

In this expression

在这个表达式中

sizeof(arr) / sizeof(arr[0])

there are used two subexpressions with the sizeof operator.

使用了两个带有 sizeof 运算符的子表达式。

This subexpression

这个子表达式

sizeof(arr)

yields the number of bytes occupied by array arr(I suppose that arris an array).

产生数组占用的字节数arr(我想这arr是一个数组)。

For example if you declared an array like

例如,如果您声明了一个数组,如

int arr[10];

then the compiler has to reserve memory that to hold 10 elements of type int. If for example sizeof( int )is equal to 4 then the compiler will reserve 10 * 4 = 40 bytes of memory.

那么编译器必须保留内存以容纳 10 个 int 类型的元素。例如,如果sizeof( int )等于 4,则编译器将保留 10 * 4 = 40 字节的内存。

Subexpression

子表达式

sizeof(arr[0])

gives the number of bytes occupied by one element in the array. You could use any index as for example

给出数组中一个元素占用的字节数。例如,您可以使用任何索引

sizeof(arr[1000])

because the expression is unevaluated. It is only important the size in bytes of the object (an element of the array) used inside the operator.

因为表达式是未评估的。仅重要的是运算符内部使用的对象(数组的元素)的字节大小。

Thus if you know the total bytes that were reserved for an array

因此,如果您知道为数组保留的总字节数

sizeof(arr)

and know how many bytes each element of the array occupies (all elements of an array have the same size) then you can calculate the number of elements in the array by using the formula

并知道数组的每个元素占用多少字节(数组的所有元素具有相同的大小),然后您可以使用公式计算数组中的元素数

sizeof(arr) / sizeof(arr[0])

Here is a simple relation. If you have an array of N elements of type T

这是一个简单的关系。如果你有一个 T 类型的 N 个元素的数组

T arr[N];

and you know the size of the memory occupied by the array then you can calculate the size of its element by using formula

并且您知道数组占用的内存大小,然后您可以使用公式计算其元素的大小

sizeof( arr ) / N == size of an element of the array. 

And vice verse

反之亦然

If you know the size of the memory occupied by the array and the size of its element you can calculate the number of elements in the array

如果知道数组占用的内存大小及其元素的大小,则可以计算数组中的元素数

sizeof( arr ) / sizeof( a[0] ) == N - number of elements in the array

The last expression you can rewrite also the following way

您也可以通过以下方式重写最后一个表达式

sizeof( arr ) / sizeof( T ) == N - number of elements in the array

because the elements of the array have type T and each element of the array occupies exactly the number of bytes that are required to allocate an object of type T.

因为数组的元素具有类型 T,并且数组的每个元素占用的字节数恰好是分配类型 T 的对象所需的字节数。

Take into acccount that usually beginners make such an error. They pass an array as an argument to a function. For example let's assume that you have a function

考虑到通常初学者会犯这样的错误。他们将数组作为参数传递给函数。例如,假设您有一个函数

void f( int a[] )
{
   // ...
}

And you pass to the function your array

然后你将你的数组传递给函数

int arr[10];
f(arr);

then the function uses the pointer to the first element of the array. In fact the function has declaration

然后函数使用指向数组第一个元素的指针。实际上该函数有声明

void f( int *a )
{
   // ...
}

So if you write for example within the function

因此,如果您在函数中编写例如

void f( int *a )
{
   size_t n = sizeof( a ) / sizeof( a[0] );
   // ...
}

then as awithin the function is a pointer (it is not an array) then you will get something like

然后因为a在函数内是一个指针(它不是一个数组)然后你会得到类似的东西

void f( int *a )
{
   size_t n = sizeof( int * ) / sizeof( int );
   // ...
}

Usually the size of a pointer equal to either 8 or 4 bytes depending of the used environment. And you won't get the number of elements. You will get some weird value.

通常指针的大小等于 8 或 4 个字节,具体取决于使用的环境。你不会得到元素的数量。你会得到一些奇怪的值。

回答by Bathsheba

It only works if arrhas not been decayed into a pointer, that is, it is an array type, nota pointer type.

它只有arr在没有衰减为指针时才有效,即它是一个数组类型,而不是一个指针类型。

sizeof(arr)is the total size occupied by the array.

sizeof(arr)是数组占用的总大小。

sizeof(arr[0])is the size of the first element in the array. (Note that zero length arrays are not permitted in C++ so this element always exists if the array itself exists).

sizeof(arr[0])是数组中第一个元素的大小。(请注意,C++ 中不允许零长度数组,因此如果数组本身存在,则该元素始终存在)。

Since all the elements will be of the same size, the number of elements is sizeof(arr) / sizeof(arr[0]).

由于所有元素的大小相同,因此元素数为sizeof(arr) / sizeof(arr[0])

回答by Wasif Anton

int- is equal to 4 bytes
sizeof(int)it means: 1 * 4 = 4

int- 等于 4 个字节
sizeof(int)这意味着:1 * 4 = 4

int arr[10]- is holding 10 int
sizeof(arr)it means: 10 * 4 = 40, we got 10 intand every intgot 4 bytes,, arrwithout the []it means all the arr.

int arr[10]- 持有 10int
sizeof(arr)意味着:10 * 4 = 40,我们得到 10 int,每个int得到 4 个字节,arr没有[]它意味着所有arr.

sizeof(arr[0])it means: 1 * 4 = 4

sizeof(arr[0])这意味着:1 * 4 = 4

sizeof(arr) / sizeof(arr[0])= 10*4 / 1*4 = 10,, and it is the length of the array.

sizeof(arr) / sizeof(arr[0])= 10*4 / 1*4 = 10, 就是数组的长度。

回答by NathanOliver

When dealing with an array (some_type name[some_size]) sizeof(name)is how many bytes the array occupies. Dividing the total size of the array by the size of one element (sizeof(name[0])) gives you how many elements are in the array.

处理数组时 ( some_type name[some_size])sizeof(name)是数组占用的字节数。将数组的总大小除以一个元素的大小 ( sizeof(name[0])) 得出数组中有多少个元素。

回答by antoxar

c++ way to use extent, which allows u to get a number of elements in Nth dimension of the array. see http://en.cppreference.com/w/cpp/types/extentfor details

c++ 使用范围的方式,它允许您获取数组第 N 维中的多个元素。有关详细信息,请参阅http://en.cppreference.com/w/cpp/types/extent

int values[] = { 1 };

std::extent<decltype(values)>::value == 1