【问题标题】:Assign a block of memory to a multidimensional array in C++将一块内存分配给 C++ 中的多维数组
【发布时间】:2012-04-02 22:16:35
【问题描述】:

我是指针/内存操作的新手,正在研究一些示例程序。我想在 C++ 中将一个二维数组分配到一个连续的内存块中。我知道我必须创建一个具有二维数组大小的缓冲区。我编写了一小段代码,用于创建缓冲区并将值分配给二维数组,但我不知道如何将数组值放入缓冲区。谁能告诉我该怎么做?我已经对其进行了相当多的研究,但找不到任何可以用我理解的术语来解释该过程的东西。我知道向量可能是一个更好的选择,但我想在继续之前掌握数组操作。

谢谢!

#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <ctime>

using namespace std;

int main()
{
 int dyn_array[5][3];
 int i;
 int j;

 srand(time(NULL));

 //Need to create a pointer to a block of memory to place the 2D array into

 int* buffer=new int[5*3]; //pointer to a new int array of designated size

 //Now need to assign each array element and send each element of the array into the buffer

 for(i=0;i<5;i++)
 {
   for(j=0;j<3;j++)
   {
     dyn_array[i][j]=rand()%40;
     cout<<"dyn array ["<<i<<"]["<<j<<"] is: "<<dyn_array[i][j]<<endl; 
   }
 }
 return 0;
}

【问题讨论】:

  • buffer[i*3+j] = dyn_array[i][j]?

标签: c++ memory-management multidimensional-array


【解决方案1】:

您可以在strides 中寻址数组,例如buffer[i * 3 + j]。这里j 是快速索引,3j 覆盖范围的范围。

您通常应该始终以这种扁平的方式存储矩形的多维数据,因为这样您将拥有一块连续的内存。

【讨论】:

  • 谢谢。这也适用于 3D 数组吗?另外,我将如何从缓冲区中检索特定的数组元素?是不是和平时一样,即。 arr[1][2]=4;还是采取不同的形式?
  • 它适用于任意数量的维度。您可以编写一个包装访问函数,但它必须是圆括号 (operator()),因为方括号只能接受一个参数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-12
  • 1970-01-01
  • 1970-01-01
  • 2012-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多