用C++将一块内存分配给多维数组

Assign a block of memory to a multidimensional array in C++

本文关键字:分配 内存 数组 一块 C++      更新时间:2023-10-16

我是指针/内存操作的新手,正在处理一些示例程序。我想在C++中将一个2D数组分配到一个连续的内存块中。我知道我必须创建一个2D数组大小的缓冲区。我写了一小段代码,创建缓冲区并为2D数组赋值,但我不知道如何将数组值放入缓冲区。有人能告诉我该怎么办吗?我已经研究了很多,但找不到任何能用我理解的方式解释这个过程的东西。我知道向量可能是一个更好的选择,但在开始之前,我想先掌握数组操作。

谢谢!

#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]。这里j是快速索引,而3j所覆盖的范围的范围。

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