gpt4 book ai didi

c - 如何在 C 中为 char** 动态分配内存

转载 作者:行者123 更新时间:2023-12-04 23:42:24 26 4
gpt4 key购买 nike

我将如何动态分配内存给这个函数中的 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;    

wordLinecounter 都是0

在此代码之前:

list = malloc(sizeof(char*)*wordLine+1);
for(i = 0;i < wordLine ; i++)
list[i] = malloc(sizeof(char)*counter);

你必须给 wordLinecounter 变量赋值

内存分配也应该在以下循环之前(外部):

 while((c = fgetc(myFile)) != EOF){
:
:
}

编辑:

新问题的第三个版本。您正在读取文件两次。所以你需要 fseek(), rewind()在第二个循环开始之前到第一个字符。

尝试:

fseek(fp, 0, SEEK_SET); // same as rewind()
rewind(fp); // same as fseek(fp, 0, SEEK_SET)

我也怀疑你计算numberOfLinesmaxNumberOfChars 的逻辑。也请检查一下

编辑

我认为你对 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));  

关于c - 如何在 C 中为 char** 动态分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14786387/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com