【问题标题】:How to allocate the needed memory of a multidimensional array in C?如何在C中分配多维数组所需的内存?
【发布时间】:2019-06-20 00:21:57
【问题描述】:

我必须编写一个读取 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 行不起作用的第一个字符。 我没有收到任何错误消息。

非常感谢您的帮助!

【问题讨论】:

  • curline 和 currchar 之前初始化过吗?
  • @Spinkoo 是的,我之前已经初始化了它们
  • fgetc() 返回 int 而不是 char。它是有意为之的。
  • @alk 但是为什么它可以打印出文件的内容?

标签: c stream fopen fgets


【解决方案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); 

【讨论】:

    猜你喜欢
    • 2021-11-15
    • 2012-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多