gpt4 book ai didi

谁能解释一下用 C 语言实现动态堆栈的输出

转载 作者:行者123 更新时间:2023-11-30 19:46:16 25 4
gpt4 key购买 nike

我尝试在 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<=8,在 main 中)谢谢

代码: #包括 #包括

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;
}

最佳答案

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

关于谁能解释一下用 C 语言实现动态堆栈的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24258482/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com