Your code assumes an increase in size
will increase the size of the native array. That isn't how arrays work in C.
Native arrays in C are fixed-length after their definition. If you want to dynamically grow a sequence of things, then you need to manage a dynamic sequence, doing it inner-loop as valid data is received.
Code
The following prompts (or lack thereof) the user in the same fashion your code apparently desired. However, a loop termination condition has been added (a mark entry of -1 will terminate the loop, as will any invalid non-convertible input).
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *marks = NULL, mark = 0;
int size = 0;
printf("Enter marks\n");
while (scanf("%d", &mark) == 1 && mark != -1)
{
// expand marks
void *tmp = realloc(marks, (size+1) * sizeof *marks);
if (tmp == NULL)
{
perror("Failed to expand marks array");
exit(EXIT_FAILURE);
}
marks = tmp;
marks[size++] = mark;
}
// TODO: use marks[0] through marks[size-1] here
for (int i=0; i<size; ++i)
printf("%d ", marks[i]);
fputc('\n', stdout);
// then free marks
free(marks);
return EXIT_SUCCESS;
}
Sample Input
1 2 3 4
5 6
7 8 9
10 -1
Output
1 2 3 4 5 6 7 8 9 10
Notes: There are more efficient geometric growth algorithms that considerably reduce the number of realloc
calls, For example, doubling the prior sequence size with each realloc
and tracking both size and capacity would reduce your number of allocations from n
to log(n)
. However, for the basic understanding of inline sequence growth, this example should suffice.