内存分配二维数组C ++新的[] [英] Allocate memory for 2D array with C++ new[]

查看:198
本文介绍了内存分配二维数组C ++新的[]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我读到一些来自用户的价值观,我需要创建的具体大小的数组我它在某种程度上是这样的:

When I read some values from the user and I need to create an array of the specific size I do it somehow like this:

#include <iostream>
using namespace std;    
unsigned* numbers;
int main()
{
int a;
cin >> a;
numbers = new unsigned[a];
}

我怎么可以用二维数组做(尺寸从用户A * B读)?

How can I do it with a 2d array(sized a*b read from the user)?

推荐答案

凡是看起来像在code一个二维数组不会在存储器中的物理二维数组,但记忆任何一个普通的块或散,这取决于你如何分配它。

Anything that would look like a 2D-Array in code will not be a physical 2D array in memory, but either one plain block of memory or scattered, depending on how you allocate it.


  • 您可以通过执行ň阵列的动态分配的N指针的另一个动态数组,像nrussel的回答表明折磨自己。

  • 您可以向量的载体,而不是像billz和阿伦C.B建议 - 这将减轻你自己管理分配的内存,但仍留给你N + 1散落分配这是不是很高性能

  • 文森特·布伦南的回答表明一个动态数组分配,含A * B元素,让你在内存中一个连续的块。再加上的std ::矢量他提到,快乐生活的内置动态内存管理:

  • You can torture yourself by doing dynamic allocation of N arrays in another dynamic array of N pointers, like nrussel's answer suggests.
  • You can make a vector of vectors instead, like billz and Arun C.B suggest - that would relieve you from managing the allocated memory yourself but still leave you with N+1 scattered allocations which is not very performant.
  • Brennan Vincent's answer suggests allocation of one dynamic array, containing a*b elements, which gives you one continuous block in memory. Combine that with the builtin dynamic memory management of std::vector he mentioned and be happy:

的std ::矢量&lt;&符号GT;矩阵(A * B);

如果你想矩阵要方便访问,包住整个事情到一个类为您提供访问二维坐标中的元素。但请从管理自己的记忆一步之遥。这只是伤害了你,谁有权维护code(和寻找纪念品泄漏)。

If you want the matrix to be convenient to access, wrap the whole thing into a class providing you access to the elements with 2D-coordinates. But please step away from managing the memory yourself. It just hurts you and anyone who has to maintain that code (and search for mem leaks).

这篇关于内存分配二维数组C ++新的[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆