简体   繁体   English

在二维数组上创建指针的动态数组

[英]Create a dynamic array of pointer over 2D Array

I'm kind of stuck since i'm trying to do what is in the title.我有点卡住了,因为我正在尝试做标题中的内容。 instinctively i would do this :我本能地会这样做:

size = 10 //(for example)
int** pieces[10][10];
pieces* = (int*)malloc(sizeof(int*)*size);

But it doesn't even compile.但它甚至不编译。

Do you have any idea ?你有什么主意吗 ? Thank you !谢谢 !

In order not to mix up the syntax with "array of pointers", you need to do this:为了不将语法与“指针数组”混淆,您需要这样做:

int (*pieces) [10][10]; // pointer to int [10][10]

And then to allow convenient access with syntax pieces[i][j] rather than (*pieces)[i][j] , drop the outer-most dimension:然后为了方便使用语法pieces[i][j]而不是(*pieces)[i][j] ,删除最外层维度:

int (*pieces) [10]; // pointer to int[10], the type of the first element of a int[10][10].

Allocate with分配与

pieces = malloc( sizeof(int[10][10]) );
...
free(pieces);

Details here: Correctly allocating multi-dimensional arrays此处的详细信息: 正确分配多维数组

you are trying to make a pointer to a pointer to an array of 2d of ints.您正在尝试创建一个指向 2d 整数数组的指针的指针。 you need to delete the bracktes ([10][10]) you should allocate an array of pointers for the rows pieces = (int**)malloc(sizeof(int*)*size);你需要删除括号 ([10][10]) 你应该为行pieces = (int**)malloc(sizeof(int*)*size);分配一个指针数组pieces = (int**)malloc(sizeof(int*)*size); and then allocate for each column with a loop like this:然后用这样的循环为每一列分配:

int i;

for (i = 0; i < size; i++)
    pieces[i] = (int*)malloc(sizeof(int));

afterwards you will need to free all the column allocations and then first row allocation of pieces.之后,您将需要释放所有列分配,然后是第一行分配的部分。

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

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