I have to write a program that stores and prints out integers from memory. I have to use realloc. Basically, the program allocates size for 2 ints. When input is given 2 ints it should reallocate space for 1 more int and prints out double. Next, when input is given 3 ints, it should allocate 2 more spaces for int and prints out double.. and so on..
Test cases:
input file in.0:
------
4
------
expected output:
------
4
------
=================================================
input file in.1:
------
4 5
------
expected output:
------
4
5
double
------
==================================================
input file in.2:
------
4 5 3
------
expected output:
------
4
5
double
3
double
------
===================================================
input file in.3:
------
4 5 3 2 9
------
expected output:
------
4
5
double
3
double
2
9
double
I wrote this program but it does not allocate memory properly. Can someone guide me in the write direction please?
int main(void)
{
int c;
int digit;
int count = 0;
int d_size = 1;
int init_size = 2;
int *p = (int *) malloc(sizeof(int) * init_size);
while((c = scanf("%i", &digit)) != EOF)
{
if (c == 1)
{
*(p+count) = digit;
count++;
}
else
{
printf("not valid");
}
printf("%i\n", digit);
if (count >= 2)
{
printf("double\n");
p = (int *) realloc(p, sizeof(int) * d_size);
d_size = d_size * 2;
}
}