我已经编写了一个相当简单的堆栈实现,它会在需要时自动增加其内部数组缓冲区。
为此,我自然会使用 realloc - 它有效,但是,所有数组元素在 realloc() 调用后都按相反顺序排列。
有问题的代码:
- header :include/pd/stack.h
- 来源:src/stack/stack.c
此示例将触发所述行为:
#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/