Since the values go from 1
to 9
, you can use 0
as a sentinel for each row, that way you don't need to predict or store the number of numbers in each line, you just store all the numbers that appear, and the add a 0
at the end that will help you know where the numbers end, something identical to how c handles strings.
The following code does what I describe
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int
appendvalue(int ***values, int row, int column, int value)
{
void *pointer;
pointer = realloc(values[0][row], (1 + column) * sizeof(int));
if (pointer == NULL)
{
fprintf(stderr, "warning: allocating memory\n");
return 0;
}
values[0][row] = pointer;
values[0][row][column] = value;
return 1 + column;
}
int
main(void)
{
FILE *file;
char buffer[100];
char *line;
int **values;
int row;
file = fopen("input.txt", "r");
if (file == NULL)
{
fprintf(stderr, "error opening the file\n");
return -1;
}
values = NULL;
row = 0;
while ((line = fgets(buffer, sizeof(buffer), file)) != NULL)
{
void *pointer;
size_t column;
while (isspace(*line) != 0)
line++;
if (*line == '\0') /* empty line -- skip */
continue;
pointer = realloc(values, (row + 1) * sizeof(int *));
if (pointer == NULL)
{
fprintf(stderr, "error allocating memory\n");
return -1;
}
values = pointer;
values[row] = NULL;
column = 0;
while ((*line != '\0') && (*line != '\n'))
{
if (isspace(*line) == 0)
column = appendvalue(&values, row, column, *line - '0');
++line;
}
column = appendvalue(&values, row, column, 0);
row += 1;
}
/* let's print each row to check */
for (--row ; row >= 0 ; --row)
{
size_t index;
for (index = 0 ; values[row][index] != 0 ; ++index)
{
printf("%d, ", values[row][index]);
}
printf("\n");
free(values[row]);
}
free(values);
return 0;
}