I have a problem with 2 functions that I have created for a program the uses the stack. However, I can’t be sure if there is an error in two functions at once, because they are interconnected. Thus, when adding a data to the stack and in its subsequent output, I get not quite the correct output.
input the 1 th element :1
input the 2 th element :2
input the 3 th element :3
So if the input goes like this, when i choose the 3rd option to output the data in stack i got such output
the elements in the stack are: 0
0
0
3
0
Here is the code:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define MAXSIZE 10
int i=1,choose;
/* i represents the number of inputted elements; choose represents the identifiers of the options in the menu.*/
int *sptr,*full,*empty;
int stack[MAXSIZE];
void push(void);
void pop(void);
void printInfo(void);
int main(){
sptr=stack; // sptr points to stack[0].
empty=stack; //empty points to stack[0]
full=stack+MAXSIZE-1; // full points to stack[9]
do{
printf("\n\t===============STACK ==============\n");
printf("\n\t 1.Push stack");
printf("\n\t 2.Pop stack");
printf("\n\t 3.Print elements of the stack");
printf("\n\t 4.Exit\n");
printf("\n\t Please choose[1-4] :");
scanf("%d",&choose);
switch(choose){
case 1:
push();
break;
case 2:
pop();
break;
case 3:
printInfo();
break;
case 4:
exit(0);
default:
printf("\n\n\t==================Input error=================");
break;
}
}while(1);
return 0;
}
void push(void){
sptr=stack+1; // sptr point to the next position of the array
if(sptr==full){
printf("\n\n ........The stack is full.......");
sptr--;
}else{
printf("input the %d th element : ",i++);
scanf("%d",sptr);
}
}
void pop(void){
if(sptr!=empty){
sptr--;
i--;
}else{
printf("\n\n\t\t ........the stack is empty.......");
i=1;
}
}
void printInfo(void){
int * temp;
temp=sptr;
printf("\n\n\t the elements in the stack are: ");
do{
if(temp!=empty){
for(i;i>=0;i--)
printf("%d\n",stack[i]);
temp--;
}else{
break;
}
}while(1);
printf("\n\n\t================END===============\n");
}