本文介绍了内存在运行时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有说我必须在指针数组从文件中读取一个未知的文本行,并在运行时分配内存的一个问题。
I have a problem which says I have to read an unknown number of text lines from a file in an array of pointers and allocate memory at runtime.
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp = fopen("file.txt","r");
char *arrp[10];
int i=1;
while(!feof(fp))
{
arrp[i]=malloc(sizeof(char)*51);
fgets(arrp[i],51,fp);
i++;
}
return 0;
}
我写了这个程序,但我不知道该怎么做不先初始化数组(* ARRP [10])。
I wrote this program but I don't know how to do it without initializing the array first (*arrp[10]).
推荐答案
我建议先计算行数。
int tmp;
int linecount = 0;
FILE *fp = fopen("file.txt","r");
while ((tmp=fgetc(fp))!=EOF) {
if (tmp=='\n')
++linecount;
}
rewind(fp); // resets the stream to beginning of file
从那里,你可以MALLOC(而不是初始化一个固定的数字)指针数组适量。
From there, you can malloc the appropriate amount of array pointers (instead of initializing a fixed number).
char** lines;
lines = malloc(linecount * sizeof(char*));
和使用与fgets正常,以便然后读每一行入行[I]
and use fgets as normal to then read each line into lines[i]
这篇关于内存在运行时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!