This code requests some heap memory with the initial buffer size of 10.
If the user enters 10 or less items, I'm ok.
but let's say he enters 4. Although I free() the array later on, I think wasted some memory because I had malloc() with size 10 already.
I know if I go over 10, the program will give me garbage.
How can I avoid setting up the initial buffer size?
How can I make an array truly dynamic? I just initiate with size 1, if I have more entries, the array expands automagically.
Code:#include <stdio.h> #include <stdlib.h> #include <ctype.h> #define STARTOFF 10 int main (void){ double *numbers; double *temp_nums; int i = 0; char response; int count; numbers = (double *)malloc(STARTOFF * sizeof(double)); if (numbers == 0){ printf("Out of memory!\n"); exit(1); } printf("Do you want to enter a number (y/n)? "); response = getchar(); while (toupper(response) == 'Y'){ printf("Enter a number: "); scanf("%lf", &numbers[i]); i++; fflush(stdin); printf("Do you want to enter a number (y/n)? "); response = getchar(); } count = i; temp_nums = (double *)malloc(count * sizeof(double)); for (i = 0; i < count; i++){ temp_nums[i] = numbers[i]; } free(numbers); numbers = temp_nums; free(temp_nums); printf("\nNumbers entered"); for (i = 0; i < count; i++){ printf("\n%.2f", numbers[i]); } printf("\n"); return 0; }