【发布时间】:2016-04-01 17:54:06
【问题描述】:
所以我的任务是继续接受用户的数字,直到用户输入负数。 我的算法应该是: 1)从 2 的大小开始。 2)每次到达末尾时大小加倍,释放旧的。 3)当用户点击负数时停止。
**我知道我没有使用free,也没有检查分配是否成功,我正在努力为你们保持代码尽可能干净。 请帮忙。
#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;
}
【问题讨论】:
-
什么是
live dynamic memory allocation??? -
您不能在静态分配的数组上调用
realloc。 -
嗯,我有一种感觉。提供任何解决方案吗? :)
-
好吧,我说的是实时分配,我的意思是它是“按需”的。只要用户不断输入数字,它就会不断增长。
-
@IsanRivkin 您应该为数组动态分配内存,然后按需重新分配。
标签: c arrays dynamic dynamic-memory-allocation