我尝试在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中) 感谢
代码: #包括 的#include
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;
}
答案 0 :(得分:0)
你的缓冲区不够大。 realloc(s->arr,s->capacity);
应为realloc(s->arr,s->capacity * sizeof(int));