简体   繁体   English

更改结构中的数组大小

[英]Change array size inside a struct

I'm trying to simulate a stack (pushing and poping values into the top of the stack) using structs and dynamic memory allocation in C and I have this struct: 我正在尝试使用C语言中的结构和动态内存分配来模拟堆栈(将值推入并弹出堆栈顶部),我有这样的结构:

...
#define max 5

typedef struct stack  
{
    int stk[max];
    int top;
}STACK;
...

I successfully simulated the stack, but when it reaches its maximum size (stack is full) I want to change the value of max in order to keep adding (push) values to the top of the stack. 我成功地模拟了堆栈,但是当它达到其最大大小(堆栈已满)时,我想更改max的值,以便继续将(推)值添加到堆栈的顶部。 In other words, i just want to reallocate the max value in the stk field of the struct, if that is possible. 换句话说,我只想重新分配结构的stk字段中的最大值,如果可能的话。

Any suggestion is appreciated. 任何建议表示赞赏。

Using int stk[max]; 使用int stk[max]; is not dynamic memory allocation. 不是动态内存分配。

You need to have pointer int * stk; 你需要有指针int * stk; and initialize it with malloc . 并使用malloc初始化它。 Then realloc when more memory is needed. 然后在需要更多内存时重新realloc And when stack is no longer needed, release it with free . 当不再需要堆栈时, free释放它。

Try it like this: 试试这样:

typedef struct stack
{
  int *stk;
  int top;
}

signed int array_resize(stack *s, size_t size)
{
  if(!s) return -1;

  s->stk = realloc(s->stk, size * sizeof(int));

  return 0;
}

This reallocates the space for the array of integers. 这将重新分配整数数组的空间。 I don't know how else to make this work. 我不知道如何使这项工作。

As @user694733 as pointed out you must use dynamic memory. 正如@ user694733指出的那样,你必须使用动态内存。 An other example can be: 另一个例子可以是:

typedef struct stack  
{
    int top;
    int max;
    int stk[];
}STACK;

STACK *init_stack(int m){
    STACK *st = (STACK *)malloc(sizeof(STACK)+m*sizeof(int));
    st->top = 0;
    st->max = m;
    return st;
}

STACK *resize_stack(STACK *st, int m){
    if (m<=st->max){
         return st; /* Take sure do not kill old values */
    }
    STACK *st = (STACK *)realloc(sizeof(STACK)+m*sizeof(int));
    st->max = m;
    return st;
}

Now you can use that function in your program like: 现在您可以在程序中使用该功能,例如:

void main(void){
    STACK *st = init_stack(5);
    .... do something bu you need more room....
    st = resize_stack(st,100);
    ..... Now is small again .....
    st = resize_stack(st,5);
} 

Take care that every realloc call have a linear cost and so you cannot use it to add just a constant number of elements: better use a geometric expansion. 请注意每个realloc调用都具有线性成本,因此您不能使用它来添加常量元素:更好地使用几何扩展。 Take a look to http://en.wikipedia.org/wiki/Dynamic_array as a start point for dynamic array. 看看http://en.wikipedia.org/wiki/Dynamic_array作为动态数组的起点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM