为了动态分配的二维数组:
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
更新为上一个块。您可以从单个链表开始遍历并从头开始遍历或使用双链接。
可以使用函数'realloc'稍后改变所述阵列的大小。 – Jonathon
我会去查看该功能,并尝试考虑如何实现它,我会尽快回复给您,谢谢 – Rob