如何在C中分配多维数组所需的内存?
How to allocate the needed memory of a multidimensional array in C?
我必须编写一个读取 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 行的第一个字符,但这是行不通的。
我没有收到任何错误消息。
非常感谢您的帮助!
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);
我必须编写一个读取 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 行的第一个字符,但这是行不通的。 我没有收到任何错误消息。
非常感谢您的帮助!
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);