在堆栈上使用realloc() [英] Using realloc() on a Stack

查看:83
本文介绍了在堆栈上使用realloc()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一些简单的Stack操作,其数据结构是一个数组.

I am writing some simple Stack operations with my data structure being an Array.

#define DEFAULT_VAL 10        //in a separate Header file
int *stacky = (int*) malloc (default_size * sizeof(int));

目标是编写一个函数来动态设置Stack的大小,同时确保不丢失元素.

The objective is to write a function to dynamically set the size of the Stack while ensuring that the elements are not lost.

这是我到目前为止所拥有的:

Here is what I have so far:

void Sizer( int size)
{
  #undef DEFAULT_VAL
  #define DEFAULT_VAL size
  maxSize = size;
  int *newbuffer = (int*) realloc (stacky, size);
  if(newbuffer == NULL) //checking if the 'realloc' was successful :)
    {
      printf("PROBLEM HERE :)");              
    }
  else
    {
      stacky = newbuffer;     
    }
}

在我的 main()函数中:

int main()
{
  int i;
  for( i=1; i<15; i++) 
   {
     push(i);
   }
  Sizer(9);
  displayStack();
  Sizer(17);
  displayStack();
}

输出为:

DEFAULT_VAL is now: 9
        9. 9
        8. 8
        7. 7869816
        6. 7877384
        5. 17278
        4. 385207786
        3. 3
        2. 2
        1. 1

DEFAULT_VAL is now: 17
        9. 9
        8. 8
        7. 7869816
        6. 7877384
        5. 17278
        4. 50331651
        3. 3
        2. 2
        1. 1

任何建议都值得赞赏!谢谢

Any advice is appreciated! Thanks

推荐答案

从手册页开始:

realloc()函数更改所指向的内存块的大小到ptr的大小为字节.

所以代替:

int *newbuffer = (int*) realloc (stacky, size);

您可能想要

int *newbuffer = (int*) realloc (stacky, size * sizeof(int));

BTW:使用 malloc 和朋友时无需强制转换.参见我是否强制转换malloc的结果?

BTW: No need for cast when using malloc and friends. See Do I cast the result of malloc?

这篇关于在堆栈上使用realloc()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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