使用 realloc 更改 c 中数组的大小 [英] changing size of array in c using realloc

查看:74
本文介绍了使用 realloc 更改 c 中数组的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 ansi-C 中遇到了问题.我正在尝试在数组上使用 C 进行堆栈.但是我遇到了 pop 和 push 函数的问题——我不知道如何改变数组的大小.我想我可以使用函数 realloc() 以某种方式实现它,但我不知道如何.

I've got a problem in ansi-C. I'm trying to make stack in C on arrays. But I've got a problem with functions pop and push - I don't know how to change size of array. I think I can make it somehow using function realloc(), but I dont know how.

有人可以帮忙吗?

推荐答案

这是一个示例代码:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
    int *array = NULL;
    array = malloc(5*sizeof(*array));
    if (array == NULL)
    {
        printf("Memory allocation error\n");
        exit(1);
    }
    /* Now array has 5 entries, from 0 to 4 */
    array[0] = array[1] = array[2] = array[3] = array[4] = 0;
    array = realloc(array, 10*sizeof(*array));
    if (array == NULL)
    {
        printf("Memory allocation error\n");
        exit(1);
    }
    /* Now array has 10 entries, from 0 to 9 */
    array[5] = array[6] = array[7] = array[8] = array[9] = 0;
    free(array);
    array = NULL;
}

请注意,您不能更改从堆栈或数据(或 bss)段分配的数组的大小.您需要使用 malloc() 动态分配数组,以便您以后可以使用 realloc().

Note that you can't change the size of an array allocated from the stack or from the data (or bss) segment. You need to allocate the array dynamically using malloc() so that you can use realloc() later.

考虑在您未来的实现中,每次将新数据推送到堆栈时调用 realloc() 效率太低.传统的做法是通过至少将数组乘以 2 来扩展数组容量,并在当前大小之外保留容量(数组可以容纳的最大元素数).通常库从不收缩数组,而是在需要更多空间时扩展它.

Consider in your future implementation that calling realloc() every time a new datum is pushed to the stack is way too inefficient. The conventional practice is to expand the array capacity by at least multiplying it by 2, and by holding a capacity (max number of elements the array can hold) in addition to its current size. Usually libraries never shrink the array but expand it if it needs more space.

这篇关于使用 realloc 更改 c 中数组的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆