简体   繁体   English

在初始化的未知大小数组中使用sizeof() - C ++

[英]Using sizeof() in an initialized, unknown size array - C++

I'm new to C++ programming and I'm trying to get the size of an array. 我是C ++编程的新手,我正在尝试获得数组的大小。 Can anybody explain me why this happens? 谁能解释我为什么会这样? I've tried running the code in runnable.com and the same result shows. 我已经尝试在runnable.com中运行代码,结果相同。

I'm sure this is not the right way to do it. 我确信这不是正确的做法。 If possible, can you suggest any EASY way to get the size of that kind of array? 如果可能的话,你能建议任何简单的方法来获得那种阵列的大小吗?

#include <iostream>

using namespace std;

int main ()
{
  int set1[] = {1, 9, 3, 50, 31, 65};
  int set234[] = {3, 5, 5};

  cout << sizeof(set1) << endl;
  cout << sizeof(set234) << endl;

  cout << "When sizeof() return value is divided by 4"<< endl;
  cout << sizeof(set1) / 4 << endl; 
  cout << sizeof(set234) / 4 << endl;

  return 0;
}

****************************************************************
Output:
24
12
When sizeof() return value is divided by 4
6
3
****************************************************************

**EDIT : Thank you for your responses. **编辑:谢谢你的回复。 flies away :D 飞走了 :D

The size of an array is equal to the sum of sizes of all its elements. 数组的大小等于其所有元素的大小总和。 As in your example you deal with arrays of type int then it seems sizeof( int ) in your system is equal to 4, So as the first array has 6 elements then its size is equal to 6 * sizeof( int ) that is 24. The size of the second array is equal to 3 * sizeof( int ) that is 12. If for example sizeof( int ) in your system would be equal to 8 then the size of the first array would be equal to 48 ( 6 * sizeof* int ) ) and the size of the second array would be equal to 18 ( 3 * sizeof( int ) ). 在您的示例中,您处理int类型的数组,然后系统中的sizeof(int)似乎等于4,因此第一个数组有6个元素,那么它的大小等于6 * sizeof( int )即24。第二个数组的大小等于3 * sizeof( int ) ,即12.如果你的系统中的sizeof(int)等于8,那么第一个数组的大小将等于48(6 * sizeof) * int))和第二个数组的大小将等于18(3 * sizeof(int))。

So if you want for example to know how many elements there are in an array you can calculate this the following way 因此,如果您想要知道数组中有多少元素,您可以通过以下方式计算它

sizeof( YouArray ) / sizeof( YourArray[0] )

or 要么

sizeof( YouArray ) / sizeof( ElementType )

sizeof returns the number of bytes, not the number of elements. sizeof返回字节数,而不是元素数。 Mostly you should avoid arrays; 大多数情况下你应该避免阵列; use std::vector or std::array , both provide an easy way to get the number of elements. 使用std::vectorstd::array ,两者都提供了一种获取元素数量的简便方法。

sizeof returns the size of the array in bytes, not elements. sizeof以字节为单位返回数组的大小,而不是元素。 It looks like you're running on a 32-bit system (or LP64, meaning only longs and pointers are 64-bit, but ints are still 32), so each element in your integer array is 4 bytes. 看起来你正在运行32位系统(或LP64,这意味着只有long和指针是64位,但是int仍然是32),所以整数数组中的每个元素都是4个字节。 In your set1, which is 6 elements, that is 6x4=24 bytes. 在你的set1中,它是6个元素,即6x4 = 24个字节。

To get the size in elements, do sizeof(set1)/sizeof(set1[0]). 要获取元素的大小,请执行sizeof(set1)/ sizeof(set1 [0])。 Not however, that works for arrays where you've listed the elements at compile time. 但是,它不适用于您在编译时列出元素的数组。 If, however, you just have an int*, the sizeof operator will return the size of the pointer. 但是,如果只有int *,则sizeof运算符将返回指针的大小。

sizeof() gives you the total size in bytes. sizeof()为您提供以字节为单位的总大小。 For example, if int is 4, and you have 6 elements in array. 例如,如果int为4,则数组中有6个元素。 It'll return 4*6=24 as the answer. 作为答案,它将返回4 * 6 = 24。 Thus the following code will give you the size of an array . 因此,以下代码将为您提供数组的大小。

#include <iostream>

using namespace std;

int main ()
{
  int set1[] = {1, 9, 3, 50, 31, 65};
  int set234[] = {3, 5, 5};

  cout << (sizeof(set1))/4 << endl;
  cout << (sizeof(set234))/4 << endl;


  return 0;
}

You can also use this : 你也可以用这个:

#include <iostream>
#include <array>

int main ()
{
  array<int,5> a;
  cout << "size is" << a.size();
return 0;
}

To get the count of elements in an array allocated on the stack, the usual technique is to get the total size, in bytes, of the whole array, and then divide that by the size, in bytes, of a single array item: 要获取在堆栈上分配的数组中元素计数 ,通常的技术是获取整个数组的总大小(以字节为单位),然后将其除以单个数组项的大小(以字节为单位):

<item count> = <total array size in bytes> / <single array item size in bytes>

However, this formula can be applied only to arrays allocated on the stack , not to arrays dynamically allocated on the heap (eg using new[] ): in this latter case, you need to keep the array item count as a separate piece of information. 但是,此公式只能应用于在堆栈上分配的数组, 而不能应用于在堆上动态分配的数组(例如,使用new[] ):在后一种情况下,您需要将数组项目计数作为单独的信息保留。

Microsoft Visual C++ provides a convenient _countof() macro, that does the above calculation for you, and safely breaks the compilation process if the argument is a pointer eg to a dynamically allocated array (since in that case the above formula gives an incorrect result, ie the size of a pointer - which is fixed, eg 4 bytes on 32-bit systems, and unrelated to the pointed-to array size - divided by the size of the first pointed item). Microsoft Visual C ++提供了一个方便的_countof()宏,它为您执行上述计算,并且如果参数是一个指针(如动态分配的数组),则安全地中断编译过程(因为在这种情况下,上面的公式给出了不正确的结果,即指针的大小 - 固定的,例如32位系统上的4个字节,与指向的数组大小无关 - 除以第一个指向项的大小)。

It seems there is an equivalent safe ARRAY_SIZE() macro for Linux . 似乎Linux有一个等效的安全ARRAY_SIZE()

#include <cstddef>

template<class T, std::size_t N>
std::size_t length_of( T(&)[N] ) {
  return N;
}

is a template that solves your problem. 是一个解决您的问题的模板。

A more industrial-strength version in C++11 is: C ++ 11中更具工业级的版本是:

#include <array>

template<class T, std::size_t N>
constexpr std::size_t size( T(&)[N] ) {
  return N;
}
template<class T, std::size_t N>
constexpr std::size_t size( std::array<T,N> const& ) {
  return N;
}
template<class C,class=void>
struct has_size : std::false_type {};
template<class>using void_t=void;
template<class C, void_t< decltype( std::declval<C&>().size() ) > >
struct has_size : std::true_type {};

template<bool b, class T=void>using enable_if_t=typename std::enable_if<b,T>::type;

template<class C, class=enable_if_t< has_size<C>::value, bool[1] >>
constexpr std::size_t size( C const& c ) {
  return c.size();
}

template<class C, class=enable_if_t< !has_size<C>::value, bool[2] >>
constexpr std::size_t size( C const& c ) {
  using std::begin; using std::end;
  return end(c)-begin(c);
}

which probably goes too far. 这可能太过分了。 Note that non-random access iterators in containers that lack a size will probably fail to compile (as - is usually not defined), which is sort of on purpoes (we don't want to accidentally do O(n) work). 请注意,缺少大小的容器中的非随机访问迭代器可能无法编译(因为-通常没有定义),这类似于purpoes(我们不想意外地执行O(n)工作)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM