So My mission is to keep accepting numbers from users until the user input a negative number. My algorithm should be: 1)start in the size of 2. 2)double the size every time it reaches the end, free the older one. 3) stop when user hits negative number.
**I know I haven't used free and didn't check if the allocation is successful, I'm trying to keep the code as clean as possible for you guys. Please help.
#include <stdio.h>
#include <stdlib.h>
int *reallocate(int* numbers,int i,int arr[]);
int main() {
int numbers[2];
int *nums = numbers;
int i = 0;
int size = 2;
while (i<size)
{
scanf("%d", (nums+i));
if (*(nums + i) <0)
break;
i++;
if (i == size) {
nums=reallocate(nums,i,numbers);
size = size * 2;
}
}
puts("Stop");
return 0;
}
int *reallocate(int* numbers,int i, int arr[]) {
int newsize = 0;
newsize =i * 2 * sizeof(int);
numbers = (int *)realloc(arr,newsize);
return numbers;
}