【问题标题】:How to create live dynamic memory allocation in an array of numbers, while taking input?如何在输入的同时在数字数组中创建实时动态内存分配?
【发布时间】: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


【解决方案1】:

您应该仅将malloc'ed 数组与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;
    }
}

【讨论】:

  • 效果很好,谢谢!我弄错了制作静态数组并指向它的想法,谢谢! *小修正,你忘了在 realloc 中添加 sizeof(int),仅供阅读这里的人使用,但效果很好!
  • 你为什么要投射malloc?顺便说一句,您的代码存在内存泄漏。
  • @Michi 你能告诉我在哪里吗?关于铸造malloc,你有什么想法如何在C而不是C++中做到这一点(我的意思是没有vector)?
  • @stek29 我真的不明白你的问题。无论如何都不需要在 C 中强制转换 malloc,因为它的返回类型是 VOID*。如果你问这个,那你可能不知道。可能是因为你习惯了C++?或者可能是因为您使用了错误的编译器
  • @stek29 malloc 发生的地方,free 也应该出现。你应该知道的。
猜你喜欢
  • 2014-05-15
  • 1970-01-01
  • 2017-07-22
  • 2021-12-20
  • 1970-01-01
  • 2013-10-05
  • 2017-06-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多