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

Sha*_*ars 2 c arrays c-strings dynamic-allocation

我将如何在此函数中动态分配内存到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++;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Gri*_*han 6

这样做:

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);  
Run Code Online (Sandbox Code Playgroud)

此外,如果您动态分配内存.你要把它当作工作来解放它:

for(i=0;i<number_of_row; i++) 
  free(list[i] );
free(list);  
Run Code Online (Sandbox Code Playgroud)

编辑

在你修改过的问题中:

 int wordLine = 0, counter = 0, i;    
Run Code Online (Sandbox Code Playgroud)

wordLine并且counter0

在此代码之前:

list = malloc(sizeof(char*)*wordLine+1);
for(i = 0;i < wordLine ; i++)
   list[i] = malloc(sizeof(char)*counter);  
Run Code Online (Sandbox Code Playgroud)

你必须赋值wordLinecounter变量

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

 while((c = fgetc(myFile)) != EOF){
  :
  :
 }
Run Code Online (Sandbox Code Playgroud)

编辑:

新问题的第三个版本.你正在读两次文件.所以你需要在第二个循环开始之前将fseek(),rewind()转换为第一个char.

尝试:

fseek(fp, 0, SEEK_SET); // same as rewind()
rewind(fp);             // same as fseek(fp, 0, SEEK_SET)
Run Code Online (Sandbox Code Playgroud)

我也怀疑你的逻辑计算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++;
}    
Run Code Online (Sandbox Code Playgroud)

maxNumberOfChars 是一行中最大字符数.

也改变代码:

malloc(sizeof(char)*(maxNumberOfChars + 1));  
Run Code Online (Sandbox Code Playgroud)