I have to write a c program that reads a txt-file. The characters of the file have to be stored in a double-pointer/ multidimensional array.
I first of all have to find out how many lines are in the txt file. The first dimension of the array is equal to the amount of lines, the second always has the size of 256. I have to allocate the memory that is needed for the array.
I already got this:
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]);
I expect the program to print out all character of the file on the console. That works fine. It should also print out the first character of line 10 which does not work. I don't get any error messages.
Thanks a lot for your help!
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);