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

How to get size of dynamic array in C++

本文关键字:数组 动态 获取 C++      更新时间:2023-10-16

通过输入大小并将其存储到"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.

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

#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' ;
}

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

当然,正确的方法是避免new[]并使用std::vector,它为您存储长度并且启动异常安全。

以下是使用 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