Reputation: 167
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;
}
Upvotes: 0
Views: 49
Reputation: 395
You should use malloc
'ed arrays only with realloc
Here is code:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *nums;
size_t size = 2;
nums = malloc(size * sizeof(int));
size_t i = 0;
while (i < size && nums != NULL) {
scanf("%d", (nums+i));
if (nums[i] < 0)
break;
i++;
if (i == size) {
size *= 2;
nums = realloc(nums, size * sizeof(int));
}
}
if (nums == NULL) {
puts("Error");
return 1;
} else {
free(nums);
puts("Stop");
return 0;
}
}
Upvotes: 1