【问题标题】:can anyone explain the output of this implementation of Dynamic Stack in C谁能解释这个用 C 语言实现的动态堆栈的输出
【发布时间】:2014-08-07 03:37:46
【问题描述】:

我尝试在 C 中实现动态数组,每次发现堆栈已满时,其大小都会翻倍。当我尝试推送超过 8 个元素时,它会失败。它给出的输出是:

stack empty (since nothing is pushed on to it yet)
|1|
yes (indicates: double operation called)
|2|
yes
|3|
|4|
yes
|5|
|6|
|7|
|8|
yes

谁能解释为什么它只适用于最大 8 的堆栈大小(n

代码: #包括 #包括

struct stkarr{              //structure for a node
     int top;
     int capacity;
     int *arr;
};

struct stkarr* buildstk(){ //build an object stack (s)
    struct stkarr *s = (struct stkarr*)malloc(sizeof(struct stkarr));
    // since it's a dynamic array we start with capacity = 1
    s->capacity=1;
    s->top=-1;
    s->arr = (int*)malloc(s->capacity*sizeof(int));
    return s;
};

int is_stk_full(struct stkarr* s){
    return(s->top==s->capacity-1); // 1->yes, 0->no
}

int is_stk_empty(struct stkarr* s){
    return(s->top==-1);
}

void dbl_stk(struct stkarr *s){//doubling the size of stack
    (s->capacity)*=2;
    s->arr = realloc(s->arr,s->capacity);
}

void psh(struct stkarr* s,int val){ //push
    if(is_stk_full(s)){
    printf("yes\n");
    dbl_stk(s);
    }
        s->arr[++s->top] = val;
}

int pop(struct stkarr* s){
    if(is_stk_empty(s)){
        printf("stack empty\n");
        return;
    }
    else{
        return s->arr[s->top--];
    }
}

int main(){
    struct stkarr* s;
    int i,n;
    n=10;
    s = buildstk();
    //checking empty stack exception
    pop(s);

    for(i=0;i<n;i++){
        //push operation
        psh(s,i+1);
        printf("|%d|\n",pop(s)); // just checking if i+1 is pushed or not
        psh(s,i+1); // since I popped i+1, pushing it again on to stack
    }

    //never reaches here for n>8
    for(i=0;i<n;i++){//popping elements and printing them
        //pop operation
        printf("|%d|\n",pop(s));
    }

    return 0;
}

【问题讨论】:

  • 编译所有警告和调试信息(例如使用gcc -Wall -g)。然后使用调试器(例如gdb

标签: c dynamic stack


【解决方案1】:

您的缓冲区不够大。 realloc(s-&gt;arr,s-&gt;capacity); 应该是 realloc(s-&gt;arr,s-&gt;capacity * sizeof(int));

【讨论】:

  • 谢谢,这是一个最愚蠢的错误。
猜你喜欢
  • 2011-08-24
  • 1970-01-01
  • 2017-09-12
  • 2012-06-21
  • 1970-01-01
  • 1970-01-01
  • 2018-04-25
  • 2021-02-27
相关资源
最近更新 更多