如何在C++中获取动态数组的大小
How to get size of dynamic array in C++
通过输入大小并将其存储到"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
相关文章:
- std::向量与传递值的动态数组
- 将数组动态分配到具有指针参数的函数中
- 我可以以某种方式使我的矢量/数组动态更改装置数量吗?
- 使用 new: "potentially uninitialized pointer"将对象数组动态分配给指针
- 为什么C 没有方便的方式来为多维数组动态分配内存
- 如何制作具有动态大小的数组?动态数组的一般用法(可能还有指针)
- c++中的数组动态内存分配
- 多维数组动态分配的内存图
- 如何在 c++ 中使用 2-D 固定数组为 4-D 数组动态分配内存
- C++ 我在数组/动态内存方面遇到了一些问题
- C++ 中从数组动态强制转换
- C++中高维数组动态内存分配的正确方法.
- 从 C++ 结构中包含的指针数组动态分配和访问内存
- 对象数组动态内存分配
- 为二维数组动态分配内存时出错
- 如何将2d数组动态分配给结构
- 为结构数组c++动态分配内存
- 将数组动态添加到多维数组
- 类中的类数组-动态数组(c++)有问题
- 分配对象数组动态冻结