如何将连续的内存块(动态地)添加到先前分配的动态内存中

How to add contiguous blocks of memory (dynamically) to a previosly allocated dynamic memory

本文关键字:内存 动态 添加 分配 连续      更新时间:2023-10-16

我正在与Arduino合作。我的主要任务是将整个房间划分成小网格,并使用超声波传感器绘制房间内的障碍物地图
为此,我希望动态分配内存。现在,这些传感器最多只能探测4米。所以我会把这个距离分成块,然后分配内存。但随着机器人的前进,它将发现更多的空间,并需要在之前分配的内存上添加更多的内存。

因此,这是一个将连续的内存块添加到先前分配的内存中的问题。

这只是代码中与问题相关的一小部分。

//max_x and max_y are the number of blocks in x and y direction respectively.
int **grid = new *int[max_x];              
for(int i = 0; i <max_x; i++)
{
    int grid[i] = new int[max_y];
}
void foo();   //stores some values in the previously allocated memory.
dist_y = get_y();      //returns blocks available in y direction.
dist_x = get_x();      //returns blocks available in x direction.
if((dist_y > max_y) | (dist_x > max_x))
{
    append_grid((max_x-dist_x),(max_y-dist_y));  //add these many number of blocks.
}  

那么,如何根据测量的距离增加更多的内存呢?

我想这就是你试图做的

#include <iostream>
using namespace std;
int max_x=10;
int max_y=12;
int** changeXY( int** g, int newX, int newY ){
int** temp = new int*[newY];
for(int i = 0; i < newY; i++)
    temp[i] = new int[newX];
for( int y = 0; y < max_y; y++)    
    for( int x = 0; x < max_x; x++)
        temp[x][y] = g[x][y];
        delete[] g;
        return temp;
}
int main() {
//Its easier to think about what you are creating as a vector
//full of vectors rather than a grid. Here you are creating a 
//pointer to a string of pointers of size max_y
//or assigning the number of columns
int **grid = new int*[max_y];            
//here you are making a loop to add elements to the pointer
//array you just created. if the pointer syntax is confusing remember
//that "grid[i]" is equivalent to "*(grid + i)"
for(int i = 0; i < max_y; i++)
    grid[i] = new int[max_x];   
grid = changeXY(grid,22,20);
delete[] grid;
return 0;
}

你的语法有几个错误。首先,当您声明一个动态内存时,语法是"new int*[max_y]",这实际上是在告诉编译器要指定什么类型。其次,在循环中添加另一个尺寸标注时,就是将其添加到栅格中。不是第一个维度。

哦,顺便说一句!按照我写这篇文章的方式,没有处理,除非max_y和max_x像本例中那样是全局的,否则changeXY()函数也必须将它们包含在输入参数中。希望这能有所帮助。

既然我知道了std::vector,我想我可以用它来解决这个问题。我还没有发布整个代码,因为我认为它会添加太多不相关的细节。

vector<vector<int> > grid;
dist_y = get_y();        //returns the number of blocks in Y direction
if(dist_y > threshold){
    forward();          //moves a step forward.
    dist_x = get_x();   //returns blocks available in X direction.
    vector<int> col;
    for(int i = 0; i < dist_x; i++) {
        col.push_back(1);   //1 indicates there is free space there.
    }
    grid.push_back(col);
}  

重复此循环将根据需要不断添加元素。