Hi! I just started learning a bit more intermediate C and I am implementing the Convex Hull algorithm. Now the problem I face is I don't want the user to have to enter the number of points he has. So this is how i currently handle that:
First there is an array dynamically allocated where the user input is stored.
It keeps reading user input until user enters -1.
Everytime user enters a number that is not -1 size is increased by one.
Then a new array is allocated size*sizeof(int)
All the known data from readbuffer is then transfered to the new array and the readbuffer is freed.
If I understand this correctly the program uses a lot of memory at the begging then a lot is freed.
NOTE: init_memsize defines the max amount of points allowed. I know that I need 2 dimension to define a point but this question is purely about memory and efficiency.
CODE:
Code:#include <stdio.h> #include <stdlib.h> int main(){ int size = 0; int init_memsize = 100000*sizeof(int); int* readbuffer = (int*) malloc(init_memsize); bool endread = false; int temp; while(!endread){ scanf("%d", &temp); if(temp>0){ readbuffer[size++]=temp; }else{ endread = true; } } int memsize = size*sizeof(int); int* data = (int*) malloc(memsize); for(int i = 0; i<=size; i++){ data[i] = readbuffer[i]; } free(readbuffer); /*Actual alogrithm code would go here*/ free(data); }