Reputation: 11
I want to implement a stack of strings wherein every element of a stack represents a string. For example I input names of people as elements. I have written the following code but the display is not working.
#include <stdio.h>
#include <stdlib.h>
#define max 5
struct stack{
int top;
char *stack[100];
};
typedef struct stack stack;
void push(struct stack *s)
{
char element[20];
if (s->top == max-1)
{
printf("Stack is full\n");
return;
}
else
{
s->top+=1;
printf("Enter the element to be pushed\n");
scanf("%s",element);
for(int i=0;element[i]!='/0';i++)
*(s->stack[s->top])=element;
}
}
void pop(struct stack *s)
{
if (s->top == -1)
{
printf("Stack is empty\n");
return;
}
else
{ printf("The element deleted is %s\n",*(s->stack[s->top]));
s->top-=1;
}
}
void display(struct stack *s)
{
if (s->top == -1)
{
printf("Stack is empty\n");
return;
}
else
{
for (int i=0;i<=s->top;i++)
{
printf("%s\n",*(s->stack[i]));
}
}
}
int main()
{
struct stack s;
s.top=-1;
int ch;
for(;;)
{
printf("Enter your choice\n1.Push\n2.Pop\n3.Display\n4.Exit\n");
scanf("%d",&ch);
switch (ch)
{
case 1:
push(&s);
break;
case 2:
pop(&s);
break;
case 3:
display(&s);
break;
case 4:
goto a;
break;
default:
printf("Invalid choice");
break;
}
}
a:
return 0;
}
This is an example of the expected terminal : Enter your choice 1.Push 2.Pop 3.Display 4.Exit 1 Enter the element to be pushed john Enter your choice 1.Push 2.Pop 3.Display 4.Exit 1 Enter the element to be pushed maddy Enter your choice 1.Push 2.Pop 3.Display 4.Exit 3 The elements are: john maddy
Upvotes: 1
Views: 80
Reputation: 7051
I looked only at the push()
part of your code.
You have char *stack[100];
which is an array of 100 character pointers.
You need char stack[5][20];
which an array of 5 strings of 20 character each.
To save the strings in the stack you need to change the copy part of your code:
for(int i=0; element[i]!='\0'; i++)
s->stack[s->top][i] = element[i];
This copies the string character for character onto the stack.
strncpy()
would be a better way of doing this.
strncpy(s->stack[s->top], element, 20);
Look at all the comments on your question as well for other problems and code smells. There a still still some other problems remaining.
Upvotes: 1