#include
#include
#define STACK_INIT_SIZE 10
#define STACKINCREMENT 2
struct Stack
{
char base;
char *top;
int stacksize;
};
struct Stack *InitStack(struct Stack *S) //創建空棧
{
S->base=(char *)malloc(STACK_INIT_SIZE * sizeof(char));
if(!S->base) {printf("error!"); return 0;}
S->top=S->base;
S->stacksize=STACK_INIT_SIZE ;
return S;
}
struct Stack *Push(struct Stack *S,char e) //向棧中插入元素
{
if(S->top-S->base==S->stacksize)
{
S->base=(char *)realloc(S->base,(S->stacksize+STACKINCREMENT * sizeof(char)));
if(!S->base) {printf("分配空間失敗"); return 0;}
S->top=S->base+S->stacksize;
S->stacksize+=STACKINCREMENT;
}
*(S->top)=e;
S->top++;
return S;
}
void Pop(struct Stack *S,char e) //刪除棧頂元素,並且返回其值
{
if(S->top==S->base) {printf("棧為空,無法刪除棧頂元素"); return 0;}
e=(--S->top);
printf("刪除的棧頂元素為:");
printf("%c\n",e);
}
int main()
{
struct Stack *S;
int e;
char i;
S=(struct Stack *)malloc(STACK_INIT_SIZE * sizeof(char));
if( !S->base) printf("error!");
InitStack(S);
printf("輸入要插入的元素e:");
scanf("%c",&e);
Push(S,&e);
Pop(S,&i);
return 0;
}
以上是我寫的c語言程序,運行的時候不管輸入什麼,輸出的都是x,求哪位大神講解下為什麼,實在是百思不得其解
你的代碼都不能編譯
#include<stdio.h>
#include<stdlib.h>
#define STACK_INIT_SIZE 10
#define STACKINCREMENT 2
struct Stack
{
char *base;
char *top;
int stacksize;
};
struct Stack *InitStack(struct Stack *S) //創建空棧
{
S->base=(char *)malloc(STACK_INIT_SIZE * sizeof(char));
if(!S->base) {printf("error!"); return 0;}
S->top=S->base;
S->stacksize=STACK_INIT_SIZE ;
return S;
}
struct Stack *Push(struct Stack *S,char e) //向棧中插入元素
{
if(S->top-S->base==S->stacksize)
{
S->base=(char *)realloc(S->base,(S->stacksize+STACKINCREMENT * sizeof(char)));
if(!S->base) {printf("分配空間失敗"); return 0;}
S->top=S->base+S->stacksize;
S->stacksize+=STACKINCREMENT;
}
*(S->top)=e;
S->top++;
return S;
}
void Pop(struct Stack *S,char e) //刪除棧頂元素,並且返回其值
{
if(S->top==S->base) {printf("棧為空,無法刪除棧頂元素"); return; } //void函數不能return 0;
e=*(--S->top);
printf("刪除的棧頂元素為:");
printf("%c\n",e);
}
int main()
{
struct Stack *S;
char e; // 不能是int
char i;
S=(struct Stack *)malloc(STACK_INIT_SIZE * sizeof(char));
if( !S->base) printf("error!");
InitStack(S);
printf("輸入要插入的元素e:");
scanf("%c",&e);
Push(S,e); //函數裡要求char,這裡不能取地址
Pop(S,i); // 同上
return 0;
}