我将如何在此函数中将内存动态分配给char **列表?
基本上,该程序的思想是我必须从文件中读取单词列表。我不能假设最大字符串或最大字符串长度。
我必须使用C弦做其他事情,但是我应该会满意。
谢谢!
void readFileAndReplace(int argc, char** argv)
{
FILE *myFile;
char** list;
char c;
int wordLine = 0, counter = 0, i;
int maxNumberOfChars = 0, numberOfLines = 0, numberOfChars = 0;
myFile = fopen(argv[1], "r");
if(!myFile)
{
printf("No such file or directory\n");
exit(EXIT_FAILURE);
}
while((c = fgetc(myFile)) !=EOF)
{
numberOfChars++;
if(c == '\n')
{
if(maxNumberOfChars < numberOfChars)
maxNumberOfChars += numberOfChars + 1;
numberOfLines++;
}
}
list = malloc(sizeof(char*)*numberOfLines);
for(i = 0; i < wordLine ; i++)
list[i] = malloc(sizeof(char)*maxNumberOfChars);
while((c = fgetc(myFile)) != EOF)
{
if(c == '\n' && counter > 0)
{
list[wordLine][counter] = '\0';
wordLine++;
counter = 0;
}
else if(c != '\n')
{
list[wordLine][counter] = c;
counter++;
}
}
}
最佳答案
这样做:
char** list;
list = malloc(sizeof(char*)*number_of_row);
for(i=0;i<number_of_row; i++)
list[i] = malloc(sizeof(char)*number_of_col);
此外,如果要动态分配内存。您将在完成工作后将其释放:
for(i=0;i<number_of_row; i++)
free(list[i] );
free(list);
编辑
在您修改的问题中:
int wordLine = 0, counter = 0, i;
wordLine
和counter
是0
在此代码之前:
list = malloc(sizeof(char*)*wordLine+1);
for(i = 0;i < wordLine ; i++)
list[i] = malloc(sizeof(char)*counter);
您必须为
wordLine
和counter
变量赋值另外,内存分配应在以下循环(外部)之前:
while((c = fgetc(myFile)) != EOF){
:
:
}
编辑:
新增您的第三版问题。您正在读取文件两次。因此,在第二个循环开始之前,您需要fseek(), rewind()到第一个字符。
尝试:
fseek(fp, 0, SEEK_SET); // same as rewind()
rewind(fp); // same as fseek(fp, 0, SEEK_SET)
我也怀疑您计算
numberOfLines
和maxNumberOfChars
的逻辑。请检查一下编辑
我认为您对
maxNumberOfChars = 0, numberOfLines = 0
的计算错误,请尝试如下操作:maxNumberOfChars = 0, numberOfLines = 0, numberOfChars = 0;
while((c = fgetc(myFile)) !=EOF){
if(c == '\n'){
numberOfLines++;
if(maxNumberOfChars < numberOfChars)
maxNumberOfChars = numberOfChars;
numberOfChars=0
}
numberOfChars++;
}
maxNumberOfChars
是一行中最大字符数。还要更改代码:
malloc(sizeof(char)*(maxNumberOfChars + 1));