You can use fgets()
to read the lines, and then strtok()
to parse each line, this is a sample program, i’ve used the first element of the integer array as the array count, so you don’t need to store it in a separate variable, I did that because I assume you can have different length arrays.
int freeArray(int **array, int setCount)
{
if (array == NULL)
return 0;
while (setCount > 0)
free(array[--setCount]);
free(array);
return -1;
}
void printArray(int *const *const array, int setCount)
{
int i;
for (i = 0 ; i < setCount ; ++i)
{
const int *pointer;
int j;
pointer = array[i];
if (pointer == NULL)
continue;
for (j = 1 ; j <= pointer[0] ; j++)
printf("%d ", pointer[j]);
printf("\n");
}
}
int *parseLine(char *line, int setCount)
{
char *pointer;
int count;
char *token;
int *array;
while ((*line != '\0') && (isspace(*line) != 0))
line++;
if (*line == '\0')
return NULL;
array = NULL;
pointer = line;
count = 0;
while ((token = strtok(pointer, " ")) != NULL)
{
char *endptr;
void *tmp;
pointer = NULL;
tmp = realloc(array, (1 + ++count) * sizeof(int));
if (tmp == NULL)
{
free(array);
return NULL;
}
array = tmp;
array[0] = count;
array[count] = strtol(token, &endptr, 10);
if ((*endptr != '\0') && ((*endptr != '\n')))
fprintf(stderr, "error: the %dth %s: value of the %dth line, is not an integer\n",
count, token, setCount);
}
return array;
}
int main(int argc, char **argv)
{
char line[256];
int **array;
int setCount;
line[0] = '\0';
array = NULL;
setCount = 0;
while (line[0] != '\n')
{
void *tmp;
if (fgets(line, sizeof(line), stdin) == NULL)
return -1;
tmp = realloc(array, (1 + setCount) * sizeof(int *));
if (tmp == NULL)
return freeArray(array, setCount);
array = tmp;
array[setCount] = parseLine(line, setCount);
if (array[setCount] != NULL)
setCount += 1;
}
printArray(array, setCount);
freeArray(array, setCount);
return 0;
}
at the end I show you how to access the elements of the array of arrays by printing them, and also how to free
the malloc
ed memory.
This program will exit when you press enter, but if you type a space before pressing enter, there will be problems, I’ll let you think about a solution to that.
solved multiple line inputs in C