#include <stdio.h>
#include <stdlib.h>
char * stack = NULL;
int top = -1;
void push (char letter);
void pop();
int main()
{
char stringy [100];
stack = (char *)malloc(100*sizeof(char));
printf("Enter a String : ");
scanf("%s",stringy);
char letter = '1';
for (int i = 0 ; letter != '\0'; i ){
letter = stringy[i];
push(letter);
printf("Top = %d, Character = %c",top,letter);
}
top--;
for (top; top != -1; top){
pop();
}
return 0;
}
void push(char letter){
top ;
stack[top] = letter;
}
void pop(){
printf("%c",stack[top]);
top--;
}
THERE IS A EMPTY CHARACTER THAT IS BEING PUSHED AND I DONT KNOW WHY PLEASE HELP There is a fourth element being pushed into my stack as well which has no display on the stdout.
CodePudding user response:
Look at this loop in your code:
for (int i = 0; letter != '\0'; i ){
letter = stringy[i];
push(letter);
When the value of i
is equal to index of stringy
array where null character exists (i.e. stringy[i] is '\0'
, it will first assign that '\0'
character to letter
and then that null character is pushed to stack.
Instead of checking letter != '\0'
, you should directly check the stringy[i] != '\0'
in for
loop condition.
Few other problems in your code:
In main()
function, you are doing
top--;
for (top; top != -1; top){
pop();
}
It can be implemented in a better way, like this:
while (top != -1) {
pop();
}
A suggestion - Instead of printing character in pop()
function, better to return the character, popped from stack, from pop()
function.
Since, the size of stringy
array is 100
characters, put a restriction in scanf()
to not to read more than 99
characters (the remain one character space is for null terminating character):
scanf("