I'm trying to write a simple program that takes specific input, dynamically allocates it, outputs it and frees. The thing is it does not output it properly. The input's style is the following:
The first line is the number of lines that I need to read - i.
Then there are i lines. On each line I read one word, then an integer n that shows how many integers will proceed next and then there come n integers.
For example,
2
yellow 2 32 44
green 3 123 3213 3213
Explanation:
1st line - there must come 2 lines.
2nd and 3rd line - word + number of integers + integers.
My attempt:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, j;
int n; /* n - number of words */
char **words; /* words - array of keywords */
int **data;
scanf ("%d\n", &n);
words = (char **) malloc (n * sizeof (char *));
data = (int **) malloc (n * sizeof (int *));
for (i = 0; i < n; ++i)
{
words[i] = (char *) malloc (sizeof (char));
for (j = 0 ;; ++j)
{
words[i] = (char *) realloc (words[i], sizeof (char) * (j + 2));
scanf ("%c", &words[i][j]);
if (words[i][j] == ' ')
break;
else if (words[i][j] == '\n')
--j;
}
words[i][j] = '\0';
data[i] = (int *) malloc (sizeof (int));
scanf ("%d", &data[i][0]);
for (j = 0; j < data[i][0]; ++j)
{
data[i] = (int *) realloc (data[i], sizeof (int) * (j + 2));
scanf ("%d", &data[i][j]);
}
}
for (i = 0; i < n; ++i)
{
printf ("%s ", words[i]);
printf ("%d ", data[i][0]);
for (j = 0; j < data[i][0]; ++j)
{
printf ("%d ", data[i][j]);
}
printf ("\n");
}
for (i = 0; i < n; ++i)
{
free (words[i]);
free (data[i]);
}
free (words);
free (data);
return 0;
}
sizeof (char)? Hint: How manychars fit in achar? What's the point in multiplying or dividing by 1?