我习惯了 PHP,但我开始学习 C。我正在尝试创建一个程序,逐行读取文件并将每一行存储到一个数组中。
到目前为止,我有一个程序可以逐行读取文件,甚至打印每一行,但现在我只需要将每一行添加到一个数组中。
我的好友昨晚告诉了我一些关于它的事情。他说我必须在 C 中使用多维数组,所以基本上是 array[x][y]
。 [y]
部分本身很简单,因为我知道每行的最大字节数。但是,我不知道该文件有多少行。
我想我可以让它循环遍历文件,每次只增加一个整数并使用它,但我觉得可能有更简单的方法。
在正确的方向上有任何想法甚至暗示吗?感谢您的帮助。
最佳答案
动态分配二维数组:
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 中)更好。
我认为还有另一种方式。在 block 中分配数组并在出现溢出时将它们链接起来。
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;
在此之后,第一个 block 就可以使用了。当您需要插入一行时,只需执行以下操作:
/* get line into buffer */
file.line[n] = malloc (sizeof (char) * (strlen (buffer) + 1));
n++;
当 n
为 LINE_MAX
时,分配另一个 block 并将其链接到这个 block 。
struct _lines *temp;
temp = malloc (sizeof (struct _lines));
temp->line = malloc (sizeof (char *) * LINE_MAX);
temp->n = 0;
file->next = temp;
file = file->next;
像这样。
当一个 block 的n
变为0
时,释放它,并将当前 block 指针file
更新为前一个。您可以从头开始遍历单链表并从头开始遍历,也可以使用双链表。
关于c - 如何为二维数组分配和释放堆内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7221981/