如何在C中分配多维数组的所需内存?

时间:2019-01-26 10:39:29

标签: c stream fopen fgets

我必须编写一个读取txt文件的c程序。文件的字符必须存储在双指针/多维数组中。

我首先必须找出txt文件中有多少行。数组的第一个维度等于行数,第二个维度始终为256。我必须分配数组所需的内存。

我已经知道了:

typedef struct _content {
    int length;
    char **lines;    
} content_t;

...

FILE *ptr;
    ptr = fopen("C:/Users/...txt", "r");
    struct _content cont;
    cont.length = 1;    
    cont.lines = malloc(sizeof(char*)*inhalt.length); 
    cont.lines[0] = malloc(255);
char c = fgetc(ptr);

...

while(c != EOF)    
    {
        cont.lines[curline][curchar] = c;

        if(c == '\n')       //to check if there is a wordwrap
        {
            cont.length++;      
            curline++;      //indicates the current line
            cont.lines[curline] = malloc(255); //thats the line where I try to allocate the memory that will be needed
            curchar = 0;    //indicates the current character of the line
        }
        else
        {
        curchar++;
        }
        c = fgetc(ptr);    
        printf("%c", c);    //to print out the content of the file (this works perfetly fine)

    }             

...

printf("\nCharacter at 10/ 0: %c", cont.lines[10][0]);

我希望程序在控制台上打印出文件的所有字符。很好 它还应该打印出第10行的第一个字符,该字符不起作用。 我没有收到任何错误消息。

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

cont.lines[curline] = malloc(255); //thats the line where I try to allocate the memory that will be needed

 // you don't try to malloc everytime you read a char but everytime you have a new line :
  if(curchar==0)
    cont.lines[curline] = malloc(255);