简体   繁体   English

指向指针的动态内存管理(C ++)

[英]Dynamic Memory Management for a pointer to a pointer (c++)

I need some help. 我需要协助。 I have an array of pointers: 我有一个指针数组:
 int *ptr = new int[N]; 
I want a two dimensional array of pointers, which points to that one dimensional array. 我想要一个二维的指针数组,它指向该一维数组。 I know how to allocate memory for a two dimensional pointer: 我知道如何为二维指针分配内存:
 int (*nn)[4] = new int [N][4]; 

BUT: How to allocate memory for a two dimensional pointer to a pointer? 但是:如何为指向指针的二维指针分配内存? Is that possible anyway? 反正有可能吗?

I need to define neighbors on a grid. 我需要在网格上定义邻居。 Finally the connection should be like this: 最后,连接应如下所示:
 for (int Vertex = 0; Vertex < N; ++Vertex) { nn[Vertex][0] = ptr[(Vertex + 1) % N]; nn[Vertex][1] = ptr[(Vertex + N - 1)% N]; nn[Vertex][2] = ptr[(Vertex + L) % N]; nn[Vertex][3] = ptr[(Vertex + N - L) % N]; if (Vertex % L == 0) { nn[Vertex][1] = ptr[Vertex + L - 1]; } if((Vertex + 1)%L == 0){ nn[Vertex][0] = ptr[Vertex - L + 1]; } } 

I just got stuck in allocating the memory... 我只是停留在分配内存上...

If you want a two dimensional array of pointers to int, you actually need a pointer to a pointer to a pointer to int, and you need to allocate the memory in a for-loop, like this: 如果要使用二维数组指针指向int,则实际上需要一个指向int指针的指针,并且需要在for循环中分配内存,如下所示:

int *** nn = new int**[N];
for(int i=0; i<N; i++) nn[i] = new int*[4];

Now nn[x][y] is a pointer to an int and *(nn[x][y]) is an int. 现在nn [x] [y]是一个指向int的指针,*(nn [x] [y])是一个int。

It is true what the comments say, though, ptr is not an array of pointers. 注释说的是对的,但是ptr不是指针数组。 However, you can still make nn point to the values of ptr by doing this: 但是,您仍然可以通过执行以下操作使nn指向ptr的值:

nn[x][y] = ptr+index;

and NOT: 并不是:

nn[x][y] = ptr[index];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM