小磊学编程 发表于 2008-5-12 12:11

求助:执行出错,怎么改

#include<iostream.h>
#define stacksize 10
typedef struct stack{
        int data[stacksize];
        int top;
}stack;
void push(stack &l,int x){
        if(l.top==stacksize-1) throw "溢出";
        l.top++;
        l.data[l.top]=x;
}
void print(stack &l){
        for(int i=0;i<=l.top;i++)
                cout<<l.data[i]<<'\t';
}

void main(void){
        stack l;
        push(l,10);
        push(l,20);
        push(l,30);
        print(l);
}

不能执行,l.data[l.top]=x;出错,不知道怎么改
请大哥们指教

zjl138 发表于 2008-5-12 12:40

看了一下,top 没有初始化。。

小磊学编程 发表于 2008-5-12 18:03

不知道怎么改

呼呼

小磊学编程 发表于 2008-5-12 18:17

谢谢大哥,解决了

#include<iostream.h>
#define stacksize 10
typedef struct stack{
        int data[stacksize];
        int top;
}stack;
void push(stack &l,int x){
        if(l.top==stacksize-1) throw "溢出";
        l.top++;
        l.data[l.top]=x;
}
void print(stack &l){
        for(int i=0;i<=l.top;i++)
                cout<<l.data[i]<<'\t';
}

void main(void){
        stack l;
        l.top=-1;
        push(l,10);
        push(l,20);
        push(l,30);
        print(l);
}

页: [1]

编程论坛