主题:关于malloc的问题。程序背景:括号配对
#include <iostream>
#include<stdio.h>
#include<stack>
using namespace std;
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
//类型说明
typedef struct {
char * base; //设置栈底指针
char * top; //设置栈顶指针
int stacksize;
}SqStack;
//构造一个空栈S
char InitStack(SqStack *S){
S->base=(char *)malloc(sizeof(SqStack));
if(!S->base) exit (0); //存储分配失败
S->top=S->base;
S->stacksize=STACK_INIT_SIZE;
}
//插入新的栈顶元素e
char Push(SqStack *S,char e){
if(S->top -S->base >= S->stacksize){//栈满,追加存储空间
S->top =(char * )realloc(S->base,
(S->stacksize + STACKINCREMENT) * sizeof(char));
if(!S->base) exit (0); //存储分配失败
S->top =S->base +S->stacksize ;
S->stacksize +=STACKINCREMENT;
}
* S->top++=e;
}
char GetTop(SqStack *S){
return (* --S->top);
}
//弹出栈顶元素e
char Pop(SqStack *S){
if(S->top ==S->base ) return 0;//栈空,返回ERROR
--S->top ; //栈不空,用e返回栈顶元素
}
void Match(char c[20]){
int i;
SqStack *S;
InitStack(S);
for(i=0;i<20;i++){ //从首元素开始判断
if(!c[i]&&(c[i]=='('||c[i]=='[')){//是否为左括号,
Push(S,c[i]); //是,进栈
}
else if(!c[i]&&c[i]==')'){ //是否为右括号
if(!GetTop(S)&&GetTop(S)=='('){//是,判断前一括号是否为与之相对的括号
Pop(S); //是,弹栈
cout<<"success to match one pair of parenthesis "<<endl;
}
else cout<<"fail to match!"<<endl;
else if(!c[i]&&c[i]==']'){ //是否为右括号
if(!GetTop(S)&&GetTop(S)=='['){//是,判断前一括号是否为与之相对的括号
Pop(S); //是,弹栈
cout<<"success to match one pair of parenthesis "<<endl;
}
else cout<<"fail to match!"<<endl;
}
else continue;
}
}
char main()
{
int i;
char c[40];
SqStack *S;
cout<<"please input a series of parenthesises"<<endl;
cin>>c;
for(i=0;i<20;i++)
{
if(c[i]!='('&&c[i]!=')'||c[i]!='['&&c[i]!=']'){
cout<<"the chars you had put in are illegal!"<<endl;
exit(0);
}
}
Match(c);
}
这是我程序的源代码。可是出错了。我想不明白。我想先创建一个100字长的栈,如果不够用再追加。可是在用malloc创建的时候出现问题。高手们帮帮忙。关于malloc的具体应用,实在不会了