【发布时间】: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