C++ 如何在C++中获取动态数组的大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22008755/
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-27 23:53:53  来源:igfitidea点击:

How to get size of dynamic array in C++

c++dynamic-arrays

提问by evergreen

Code for dynamic array by entering size and storing it into "n" variable, but I want to get the array length from a template method and not using "n".

通过输入大小并将其存储到“n”变量中来编写动态数组的代码,但我想从模板方法中获取数组长度而不是使用“n”。

int* a = NULL;   // Pointer to int, initialize to nothing.
int n;           // Size needed for array
cin >> n;        // Read in the size
a = new int[n];  // Allocate n ints and save ptr in a.
for (int i=0; i<n; i++) {
    a[i] = 0;    // Initialize all elements to zero.
}
. . .  // Use a as a normal array
delete [] a;  // When done, free memory pointed to by a.
a = NULL;     // Clear a to prevent using invalid memory reference.

This code is similar, but using a dynamic array:

此代码类似,但使用动态数组:

#include <cstddef>
#include <iostream>
template< typename T, std::size_t N > inline
std::size_t size( T(&)[N] ) { return N ; }
int main()
{
     int a[] = { 0, 1, 2, 3, 4, 5, 6 };
     const void* b[] = { a, a+1, a+2, a+3 };
     std::cout << size(a) << '\t' << size(b) << '\n' ;
}

回答by Angew is no longer proud of SO

You can't. The size of an array allocated with new[]is not stored in any way in which it can be accessed. Note that the return type of new []is not an array - it is a pointer (pointing to the array's first element). So if you need to know a dynamic array's length, you have to store it separately.

你不能。分配的数组的大小new[]不会以任何可以访问的方式存储。请注意, 的返回类型new []不是数组 - 它是一个指针(指向数组的第一个元素)。因此,如果您需要知道动态数组的长度,则必须单独存储它。

Of course, the proper way of doing this is avoiding new[]and using a std::vectorinstead, which stores the length for you and is exception-safe to boot.

当然,这样做的正确方法是避免new[]和使用 astd::vector代替,它为您存储长度并且启动时异常安全。

Here is what your code would look like using std::vectorinstead of new[]:

这是您的代码使用std::vector而不是的样子new[]

size_t n;        // Size needed for array - size_t is the proper type for that
cin >> n;        // Read in the size
std::vector<int> a(n, 0);  // Create vector of n elements initialised to 0
. . .  // Use a as a normal array
// Its size can be obtained by a.size()
// If you need access to the underlying array (for C APIs, for example), use a.data()

// Note: no need to deallocate anything manually here