动态分配二维数组:
char **p;
int i, dim1, dim2;
/* Allocate the first dimension, which is actually a pointer to pointer to char */
p = malloc (sizeof (char *) * dim1);
/* Then allocate each of the pointers allocated in previous step arrays of pointer to chars
* within each of these arrays are chars
*/
for (i = 0; i < dim1; i++)
{
*(p + i) = malloc (sizeof (char) * dim2);
/* or p[i] = malloc (sizeof (char) * dim2); */
}
/* Do work */
/* Deallocate the allocated array. Start deallocation from the lowest level.
* that is in the reverse order of which we did the allocation
*/
for (i = 0; i < dim1; i++)
{
free (p[i]);
}
free (p);
修改上面的方法。当您需要添加另一行时,请执行 *(p + i) = malloc (sizeof (char) * dim2); 并更新 i。在这种情况下,您需要预测文件中由dim1 变量指示的最大行数,我们第一次为此分配p 数组。这只会分配(sizeof (int *) * dim1) 字节,因此比char p[dim1][dim2](在c99 中)更好。
我认为还有另一种方式。以块为单位分配数组并在溢出时将它们链接起来。
struct _lines {
char **line;
int n;
struct _lines *next;
} *file;
file = malloc (sizeof (struct _lines));
file->line = malloc (sizeof (char *) * LINE_MAX);
file->n = 0;
head = file;
在此之后,第一个块就可以使用了。当您需要插入一行时,只需执行以下操作:
/* get line into buffer */
file.line[n] = malloc (sizeof (char) * (strlen (buffer) + 1));
n++;
当n 为LINE_MAX 时,分配另一个块并将其链接到这个块。
struct _lines *temp;
temp = malloc (sizeof (struct _lines));
temp->line = malloc (sizeof (char *) * LINE_MAX);
temp->n = 0;
file->next = temp;
file = file->next;
类似的东西。
当一个块的n变为0时,释放它,并将当前块指针file更新为前一个。您可以从单链表开始遍历,也可以从头开始遍历,也可以使用双链表。