如何重新分配大小不同的2d结构指针

时间:2019-04-14 19:08:20

标签: c multidimensional-array struct malloc realloc

我想重新分配2d指针数组。它必须是动态的,如下所示

+=====+==============+==============+==============+==============+======+
|     | [0]          | [1]          | [2]          | [3]          | [..] |
+=====+==============+==============+==============+==============+======+
| [0] | 'a'          | 'b'          | 'c'          | 'd'          |      |
+-----+--------------+--------------+--------------+--------------+------+
| [1] | object[0][0] | object[1][0] | object[2][0] | object[3][0] |      |
+-----+--------------+--------------+--------------+--------------+------+
| [2] | object[0][1] | object[1][1] | object[2][1] | object[3][1] |      |
+-----+--------------+--------------+--------------+--------------+------+
| [3] | object[0][2] | object[1][2] | object[2][2] |              |      |
+-----+--------------+--------------+--------------+--------------+------+
| [4] | object[0][3] |              | object[2][3] |              |      |
+-----+--------------+--------------+--------------+--------------+------+
| [5] | object[0][4] |              |              |              |      |
+-----+--------------+--------------+--------------+--------------+------+
| [6] | object[0][5] |              |              |              |      |
+-----+--------------+--------------+--------------+--------------+------+

在此表中,每个列的大小均不同。我该如何使用2d结构。我用malloc分配了矩阵。但是我想重新分配第二个索引。像这个矩阵[25] [n]。必须为每个具有不同大小的列重新分配N。但是它必须在运行时

代码:

#include <stdio.h>
#include <stdlib.h>

typedef struct{
    char word[20];
}Dictionary;

Dictionary **object;
void initializeDictionary()
{
     // Create matrix [29][1]
     object=(Dictionary**)malloc(29 * sizeof(Dictionary*));
     object[0]=(Dictionary*)malloc(1*sizeof(Dictionary));
}

1 个答案:

答案 0 :(得分:2)

使用指针,这自然而然。在您的代码中,您有一个Dictionary**,它实际上是一个指向Dictionary的指针。但是您可以看到它是Dictionary*数组,其中每个指针指向Dictionary对象的不同大小的数组。

Dictionary** objects;
const int COLUMNS = 29;

objects = malloc(COLUMNS * sizeof(Dictionary*));

objects[0] = malloc(2 * sizeof(Dictionary)); // first column 2 elements
objects[1] = malloc(3 * sizeof(Dictionary)); // second column 3 elements

// ...

for (int i = 0; i < COLUMNS; ++i)
  free(objects[i]);

free(objects);