爲了動態分配的二維數組:
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