Hello,
I have this code which read some data from a text file. Then I save the data into a 2D array dynamically with malloc. Until codeline 57 this works fine. Then I would like to append some lines.
But at code line 59 I would like save the manipulated data into the array: char appendedLine[MAX_LINE_LENGTH], and print it.
But this does not work, and I did not know why. Can anybody help me to solve this problem?
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE_LENGTH 300 // maximal length of a line of the input file
#define MAX_LINES 100000 // lines of input file
int main()
{
// Read the lines from the file
FILE *fp = fopen("input2.txt", "r");
if (fp == NULL)
{
printf("Failed to open the file.\n");
return 1;
}
// Allocate memory for a 2D array dynamically
char **lines = (char **)malloc(MAX_LINES * sizeof(char *));
if (lines == NULL)
{
printf("Failed to allocate memory for lines.\n");
return 1;
}
for (int i = 0; i < MAX_LINES; i++)
{
lines[i] = (char *)malloc(MAX_LINE_LENGTH * sizeof(char));
if (lines[i] == NULL)
{
printf("Failed to allocate memory for line %d.\n", i);
return 1;
}
}
int lineCount = 0;
char line[MAX_LINE_LENGTH];
while (fgets(line, sizeof(line), fp) != NULL)
{
if (line[strlen(line) - 1] == '\n') // at the end of each line \n will be deleted
line[strlen(line) - 1] = '\0';
strcpy(lines[lineCount], line);
lineCount++;
if (lineCount >= MAX_LINES)
{
printf("Exceeded maximum number of lines.\n");
break;
}
}
fclose(fp);
// Append line
char appendedLine[MAX_LINE_LENGTH];
snprintf(appendedLine[0], MAX_LINE_LENGTH, "%s%s%s\n", lines[3], lines[22], lines[41]);
snprintf(appendedLine[1], MAX_LINE_LENGTH, "%s%s%s\n", lines[5], lines[24], lines[43]);
snprintf(appendedLine[2], MAX_LINE_LENGTH, "%s%s%s\n", lines[7], lines[26], lines[45]);
printf("%s\n", appendedLine[0]);
printf("%s\n", appendedLine[1]);
printf("%s\n", appendedLine[2]);
// Free the dynamically allocated memory
for(int i = 0; i < MAX_LINES; i++)
{
free(lines[i]);
}
free(lines);
return 0;
}