我正在与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.
}
那么如何根据测量的距离添加更多内存?
答案 0 :(得分:0)
我认为这就是你要做的事情
#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;
}
你的语法中有一些错误。首先,当您声明动态内存时,语法为&#34; new int * [max_y]&#34;,您实际上是在告诉编译器要指定的类型。其次,在循环中添加其他维度时,您将其添加到网格中。不是第一个维度。
哦,顺便问一下!我写这个的方式,没有处理,除非max_y和max_x是全局的,就像他们在这个例子中一样,changeXY()函数也必须在输入参数中包含它们。希望这会有所帮助。答案 1 :(得分:0)
现在我知道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);
}
重复此循环将继续根据需要添加元素。