如何在获取输入的同时在数字数组中创建实时动态内存分配?
How to create live dynamic memory allocation in an array of numbers, while taking input?
所以我的任务是不断接受用户的数字,直到用户输入负数。
我的算法应该是:
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;
}
您应该仅将 malloc
数组与 realloc
一起使用
这是代码:
#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;
}
}
所以我的任务是不断接受用户的数字,直到用户输入负数。 我的算法应该是: 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;
}
您应该仅将 malloc
数组与 realloc
一起使用
这是代码:
#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;
}
}