用C++将一块内存分配给多维数组
Assign a block of memory to a multidimensional array in C++
我是指针/内存操作的新手,正在处理一些示例程序。我想在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
是快速索引,而3
是j
所覆盖的范围的范围。
通常,您应该始终以这种扁平化的方式存储矩形多维数据,因为这样您将拥有一个连续的内存块。
相关文章:
- 在c++中为我自己的基于指针的数组分配内存的正确方法
- 给定一个指向堆分配内存的指针,智能指针实现如何为其找到合适的释放函数?
- 如果 const 不分配内存,为什么我可以获取 const 的地址?
- 在函数中分配内存时出现问题
- 如何为 std::vector 分配内存,然后稍后为某些元素调用构造函数?
- constexpr new 如何分配内存?
- 在构造函数中分配内存失败是如何冒泡的
- LLVM 传递以在特定地址分配内存
- CudaMalloc 在分配内存时失败
- 为什么它在不分配内存的情况下工作正常
- 为什么在正确解除分配内存时出现内存泄漏?
- 如何通过 malloc 为队列数组分配内存?
- vector是否为std::移动的对象连续分配内存
- 删除类成员的动态分配内存的最佳方法是什么
- 唯一指针是否在堆或堆栈上分配内存?
- 如果不分配内存,我如何能够为变量创建和分配值?
- std::initializer_list 堆是否分配内存?
- 如何按顺序或在指定的地址分配内存?
- 是否可以使用 malloc 为类对象分配内存?
- 迭代器是否分配内存(如指针)?