c - realloc:反向指针数组?

标签 c realloc

我已经编写了一个相当简单的堆栈实现,它会在需要时自动增加其内部数组缓冲区。

为此,我自然会使用 realloc - 它有效,但是,所有数组元素在 realloc() 调用后都按相反顺序排列。

有问题的代码:

此示例将触发所述行为:

#include "pd/strlib.h"
#include "pd/stack.h"
#include "pd/memory.h"
#include <stdlib.h>
#include <stdio.h>

int main()
{
    int index = 0;
    char* buffer;
    pd_stack_t* stc = pd_stack_new();
    pd_stack_push(stc, "blue");
    pd_stack_push(stc, "green");
    pd_stack_push(stc, "red");
    pd_stack_push(stc, "yellow");
    pd_stack_push(stc, "pink");
    pd_stack_push(stc, "olive");
    pd_stack_push(stc, "beige");
    pd_stack_push(stc, "gold");
    pd_stack_push(stc, "grey");
    pd_stack_push(stc, "lime");
    pd_stack_push(stc, "khaki");
    while((index++) != 500)
    {
        pd_stack_push(stc, "__random_value__");
    }
    buffer = (char*)malloc(pd_stack_size(stc));
    pd_stack_dump_tomem(stc, buffer, 1);
    fprintf(stdout, "%s", buffer);
    return 0;
}

这个我真的是一窍不通。请帮助!

最佳答案

看起来 pd_stack_dump_tomem 的索引从 堆栈大小 开始,然后递减到 0,以相反的顺序附加元素。

将其更改为从 0 开始并迭代到堆栈大小

(看来realloc是不相关的)

关于c - realloc:反向指针数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3503310/

相关文章:

c - 为什么不在这种情况下使用 free()

c - 我自己的 realloc 函数在 c 中的实现

c - C语言如何获取带两位小数的 float ?

c - 访问 MPI 拓扑中的邻居进程值

c - GCC:混合 C/汇编项目 - include 指令

arrays - 使用 realloc() 进行无效插入

c - 编写接受超时的函数的最佳方法(posix C)

c++ - 获取所有可能的组合数

c - realloc - 内存泄漏

c - 为什么动态调整字符串会导致崩溃?