Segmenation Fault - Working on stack data structure - c

I'm attempting to create a program that would allow the user to create a stack data structure using the push, pop, and peek command. However, I keep running into a segmentation fault whenever I try and use the push command! I have no idea why it's not working, because I made sure to use malloc on the stack structure. The peek and pop command are working (as far as I can tell). Any help??
#include<stdlib.h>
#include<stdio.h>
#include "stack.h"
int mainMenuChoice, pushValue;
void mainMenu() {
printf("\nEnter your option: \n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Peek\n");
printf("4. Exit\n");
scanf("%d", &mainMenuChoice);
}
Stack * initializeStack() {
Stack *new_stack;
int capacity = 100;
new_stack = (Stack *)malloc(sizeof(Stack));
new_stack->items = (int *)malloc(sizeof(int)*capacity);
new_stack->size = 0;
return new_stack;
}
void push(Stack *new_stack, int item) {
new_stack->items[new_stack->size++] = item;
}
void pop(Stack *new_stack) {
if(new_stack->size == 0) {
printf("The stack is empty, you can't pop any items!\n");
} else {
new_stack->size--;
}
}
int peek(Stack *new_stack) {
if(new_stack->size == 0) {
printf("The stack is empty.\n");
} else {
return new_stack->items[new_stack->size-1];
}
}
void menuOptions(int option) {
Stack *new_stack = initializeStack();
if(option == 1) {
Stack *new_stack;
printf("Enter an element to push: ");
scanf("%d", &pushValue);
push(new_stack, pushValue);
mainMenu();
menuOptions(mainMenuChoice);
} else if(option == 2) {
pop(new_stack);
mainMenu();
menuOptions(mainMenuChoice);
} else if(option == 3) {
peek(new_stack);
mainMenu();
menuOptions(mainMenuChoice);
} else if(option == 4) {
printf("Exiting...\n");
exit(0);
} else {
printf("Invalid input, please try again!\n");
mainMenu();
menuOptions(mainMenuChoice);
}
}
void program() {
mainMenu();
menuOptions(mainMenuChoice);
}
Also, this is the how I've structured the stack:
typedef struct Stack {
int size;
int *items;
}Stack;
Thank you so much in advance, I appreciate it!

I've simplified things a bit. You were having too many recursive calls and new_stack was being redefined [but not reallocated]. You'll still have more work to do (e.g. peek returns a value, but pop does not)
Here's the code [please pardon the gratuitous style cleanup]:
#include <stdlib.h>
#include <stdio.h>
//#include "stack.h"
typedef struct Stack {
int size;
int *items;
} Stack;
int mainMenuChoice;
int pushValue;
Stack *top_stack;
void
mainMenu()
{
printf("\nEnter your option: \n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Peek\n");
printf("4. Exit\n");
scanf("%d", &mainMenuChoice);
}
Stack *
initializeStack()
{
Stack *new_stack;
int capacity = 100;
new_stack = (Stack *) malloc(sizeof(Stack));
new_stack->items = (int *) malloc(sizeof(int) * capacity);
new_stack->size = 0;
return new_stack;
}
void
push(Stack *new_stack, int item)
{
new_stack->items[new_stack->size++] = item;
}
void
pop(Stack *new_stack)
{
if (new_stack->size == 0) {
printf("The stack is empty, you can't pop any items!\n");
}
else {
new_stack->size--;
}
}
int
peek(Stack *new_stack)
{
if (new_stack->size == 0) {
printf("The stack is empty.\n");
return -1;
}
else {
return new_stack->items[new_stack->size - 1];
}
}
void
menuOptions(Stack *new_stack,int option)
{
if (option == 1) {
printf("Enter an element to push: ");
scanf("%d", &pushValue);
push(new_stack, pushValue);
}
else if (option == 2) {
pop(new_stack);
}
else if (option == 3) {
peek(new_stack);
}
else if (option == 4) {
printf("Exiting...\n");
exit(0);
}
else {
printf("Invalid input, please try again!\n");
}
}
int
main()
{
top_stack = initializeStack();
while (1) {
mainMenu();
menuOptions(top_stack,mainMenuChoice);
}
return 0;
}

Related

Implementing linked list in C

I am trying to implement linked list in C, having options for creation, insertion, deletion and display.
My code is:
#include <stdio.h>
#include <conio.h>
void createFirst(int);
void appendNode(int);
void insertFirst(int);
void insertNode(int,int);
void deleteFirst();
void deleteNode(int);
void display();
struct Node
{
int data;
struct Node *link;
};
typedef struct Node Node;
Node *start = NULL;
int count=0;
void main()
{
int ch;
do
{
printf("\f\n");
printf("1. Create the list \n");
printf("2. Insert an element at any position \n");
printf("3. Delete an element at any position \n");
printf("4. Display the list \n");
printf("5. Quit \n");
printf("Enter your choice : \n");
scanf("%d",&ch);
switch(ch)
{
case 1:
{
int a;
char c;
printf("Enter the data : \n");
scanf("%d",&a);
createFirst(a);
while(1)
{
printf("Do you want to continue[Y/N] : \n");
scanf(" %c",&c);
if(c=='Y' || c=='y')
{
printf("Enter the data : \n");
scanf("%d",&a);
appendNode(a);
}
else if(c=='N' || c=='n')
{
break;
}
else
{
continue;
}
}
break;
}
case 2:
{
int a,pos;
char c;
printf("Enter the data : \n");
scanf("%d",&a);
printf("Enter the position : \n");
scanf("%d",&pos);
if(pos == 1)
{
insertFirst(a);
}
else
{
insertNode(pos,a);
}
while(1)
{
printf("Do you want to continue[Y/N] : ");
scanf(" %c",&c);
if(c=='N' || c=='n')
{
break;
}
if(c!='Y' && c!='y')
{
continue;
}
printf("Enter the data : \n");
scanf("%d",&a);
printf("Enter the position : \n");
scanf("%d",&pos);
if(pos == 1)
{
insertFirst(a);
}
else
{
insertNode(pos,a);
}
}
break;
}
case 3:
{
int pos;
char c;
printf("Enter the position : \n");
scanf("%d",&pos);
if(pos == 1)
{
deleteFirst();
}
else
{
deleteNode(pos);
}
while(1)
{
printf("Do you want to continue[Y/N] : ");
scanf(" %c",&c);
if(c=='N' || c=='n')
{
break;
}
if(c!='Y' && c!='y')
{
continue;
}
printf("Enter the position : \n");
scanf("%d",&pos);
if(pos == 1)
{
deleteFirst();
}
else
{
deleteNode(pos);
}
}
break;
}
case 4:
{
display();
break;
}
case 5:
{
return;
}
default:
{
printf("Invalid choice \n");
break;
}
}
}while(ch!=5);
}
void createFirst(int d)
{
Node newnode = {d,NULL};
start = &newnode;
count++;
}
void appendNode(int d)
{
Node temp = *start;
while(temp.link != NULL)
{
temp = *temp.link;
}
Node newnode = {d,NULL};
temp.link = &newnode;
count++;
}
void insertFirst(int d)
{
Node newnode = {d,NULL};
newnode.link = start;
start = &newnode;
count++;
}
void insertNode(int n,int d)
{
if(n>count || n<count)
{
printf("Invalid position \n");
return;
}
Node temp = *start;
int i;
for(i=1;i<n-1;i++)
{
temp = *temp.link;
}
Node newnode = {d,NULL};
newnode.link = temp.link;
temp.link = &newnode;
}
void deleteFirst()
{
if(start != NULL)
{
printf("Deleted element : %d \n",(*start).data);
start = (*start).link;
count--;
}
else
{
printf("Underflow \n");
}
}
void deleteNode(int n)
{
if(n>count || n<count)
{
printf("Invalid position \n");
return;
}
Node temp = *start;
int i;
for(i=1;i<n-1;i++)
{
temp = *temp.link;
}
printf("Deleted node : %d",temp.link->data);
temp = *(temp.link->link);
count--;
}
void display()
{
if(start == NULL)
{
printf("The list is empty \n");
return;
}
Node temp = *start;
int i;
for(i=1;i<=count;i++)
{
printf("%d ",temp.data);
temp = *temp.link;
}
}
But:
Whenever the control is going to appendNode function, the program terminates somehow.
After only creating the first node, if i go to display, it is printing some garbage value.
Please somebody help.
Your problem is on the line (inside of appendNode) which contains this: Node temp = *start;. Don't do it that way. Do it this way:
Node *temp = start;
Change the following pointer notations to accomodate this change. Like change the dot operators to the -> operator. Here's the rest of the function:
while(temp->link != NULL)
{
temp = temp->link;
}
Node *newnode = malloc (sizeof(struct Node));
newnode->data = 0;
newnode->link = NULL;
temp->link = newnode;
count++;

Circular Queue Operations Using Array

Code shows basic operations on Circular Queue.
#define maxsize 10
typedef struct queue
{
int data[maxsize];
int f,r;
}myQueue;
myQueue q;
void init(myQueue *q);
int full(myQueue *q);
int empty(myQueue *q);
void enqueue(myQueue *q,int num);
void dequeue(myQueue *q);
void print(myQueue *q);
void main()
{
init(&q);
int op;
do
{
printf("\nCircular queue operations: Press:\n");
printf("1 for enqueue\n");
printf("2 for dequeue\n");
printf("3 to print Circular Queue\n");
int num,choice;
printf("\nEnter choice:\n");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("Enter number to insert :\n");
scanf("%d",&num);
if(full(&q))
{
printf("\nQueue is full\n");
exit(0);
}
enqueue(&q,num);
break;
case 2: if(empty(&q))
{
printf("\nQueue is empty\n");
exit(0);
}
dequeue(&q);
break;
case 3: printf("Printing current queue: \n");
print(&q);
break;
default:break;
}
printf("Press 1 to continue or 0 to exit:\n");
scanf("%d",&op);
}
while(op);
}
void init(myQueue *q)
{
q->f=-1;
q->r=-1;
}
int full(myQueue *q)
{
if((q->r+1)%maxsize==q->f)
{
return 1;
}
else
return 0;
}
int empty(myQueue *q)
{
if(q->r==-1)
{
return 1;
}
else
return 0;
}
enqueue function is used to add the elements into queue.
void enqueue(myQueue *q,int num)
{
if(empty(&q))
{
q->f=0;
q->r=0;
}
else
{
q->r=(q->r+1)%maxsize;
}
q->data[q->r]=num;
printf("\n%d is enqueued\n",q->data[q->r]);
}
Dequeue function is used to delete elements from the stack.
void dequeue(myQueue *q)
{
int del_num;
del_num=q->data[q->f];
if(q->f==q->r)
{
init(&q);
}
else
{ //To move front to the next position in the circular array.
q->f=(q->f+1)%maxsize;
}
printf("\n%d is dequeued\n",del_num);
}
void print(myQueue *q)
{
int i;
for(i=q->f;i!=q->r;i=(i+1)%maxsize)
{
printf("%d\n",q->data[i]);
}
printf("%d\n",q->data[q->r]);
}
Issue: Circular queue is automatically enqueuing the 0 element in it initially.
However, rest of the operations are working just fine.
I am not able to identify, why it is automatically inserting 0 in the circular queue, without me enqueuing it.
Your print() function always prints q->data[q->r] as its last operation. This makes no sense when your queue is empty. Maybe you can avoid it like this:
void print(myQueue *q)
{
if (empty(q))
return;
int i;
for(i=q->f;i!=q->r;i=(i+1)%maxsize)
{
printf("%d\n",q->data[i]);
}
printf("%d\n",q->data[q->r]);
}
Anyway there are many more problems with your code, which I doubt it is compiling correctly. Just as an example, the function enqueue() receives a parameter of type myQueue*. Then it provides function empty with the address of it, but this is wrong. you have to pass the function the pointer itself, so q instead of &q. The same mistake is repeated over and over again.
1st Code Snippet requiring change:
void enqueue(myQueue *q,int num)
{
The below line is changed.
if(empty(q)==1)
{
q->f=0;
q->r=0;
}
else
{
q->r=(q->r+1)%maxsize;
}
q->data[q->r]=num;
printf("\n%d is enqueued\n",q->data[q->r]);
}
2nd code snippet requiring changed:
void dequeue(myQueue *q)
{
int del_num;
del_num=q->data[q->f];
if(q->f==q->r)
{
Line below is changed.
init(q);
}
else
{ //To move front to the next position in the circular array.
q->f=(q->f+1)%maxsize;
}
printf("\n%d is dequeued\n",del_num);
}
3rd snippet requiring change:
void print(myQueue *q)
{
int i;
Line below is changed.
if(empty(q))
{
printf("Queue empty");
exit(0);
}
else
{
printf("Printing current queue: \n");
for(i=q->f;i!=q->r;i=(i+1)%maxsize)
{
printf("%d\n",q->data[i]);
}
printf("%d\n",q->data[q->r]);
}
}
That makes it perfectly alright. :)
#include <stdio.h>
#define SIZE 5
int items[SIZE];
int front = -1, rear = -1;
int isFull() {
if ((front == rear + 1) || (front == 0 && rear == SIZE - 1)) return 1;
return 0;
}
int isEmpty() {
if (front == -1) return 1;
return 0;
}
void enQueue(int element) {
if (isFull())
printf("\n Queue is full!! \n");
else {
if (front == -1) front = 0;
rear = (rear + 1) % SIZE;
items[rear] = element;
printf("\n Inserted -> %d", element);
}
}
int deQueue() {
int element;
if (isEmpty()) {
printf("\n Queue is empty !! \n");
return (-1);
} else {
element = items[front];
if (front == rear) {
front = -1;
rear = -1;
}
else {
front = (front + 1) % SIZE;
}
printf("\n Deleted element -> %d \n", element);
return (element);
}
}
void display() {
int i;
if (isEmpty())
printf(" \n Empty Queue\n");
else {
printf("\n Front -> %d ", front);
printf("\n Items -> ");
for (i = front; i != rear; i = (i + 1) % SIZE) {
printf("%d ", items[i]);
}
printf("%d ", items[i]);
printf("\n Rear -> %d \n", rear);
}
}
int main() {
deQueue();
enQueue(1);
enQueue(2);
enQueue(3);
enQueue(4);
enQueue(5);
enQueue(6);
display();
deQueue();
display();
enQueue(7);
display();
enQueue(8);
return 0;
}

My Circular Queue implementation is not working properly

I have created a program to implement a Circular Queue with insert, delete and display. The insertion is working fine and the deletion too but once I try to enter numbers after deletion, nothing is displayed. Here is my source code:
#include<stdio.h>
#include<conio.h>
#define SIZE 5
int front = -1;
int rear = -1;
int queue[SIZE];
void enqueue(int item);
int dequeue();
void display();
void main()
{
int item, choice, cont = 1;
clrscr();
while(cont == 1)
{
printf("\n1.Enqueue into queue.\n");
printf("\n2.Dequeue from queue.\n");
printf("\n3.display quesue elements\n");
printf("\nEnter your choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nEnter the value of item: ");
scanf("%d",&item);
enqueue(item);
break;
case 2:
item = dequeue();
if(item != NULL)
{
printf("\nItem dequeued: %d\n",item);
}
break;
case 3:
display();
break;
default:
printf("\nInvalid choice.\n");
break;
}
printf("\nDo you want to continue (1/0): ");
scanf("%d",&cont);
}
getch();
}
void enqueue(int item)
{
if(front==0 && rear==SIZE-1)
printf("\n Queue OverFlow Occured");
else if(front==-1 && rear==-1)
{
front=rear=0;
queue[rear]=item;
}
else if(rear==SIZE-1 && front!=0)
{
rear=0;
queue[rear]=item;
}
else
{
rear++;
queue[rear]=item;
}
}
int dequeue()
{
int item = NULL;
if(front == -1 && rear == -1)
{
printf("\nQueue is empty. Dequeue not possible.\n");
}
else
{
item = queue[front];
queue[front] = NULL;
if(front == rear)
{
front = -1;
rear = -1;
}
else
{
front = front + 1;
}
}
return(item);
}
void display()
{
int i;
if(front==-1)
printf("\n No elements to display");
else
{
printf("\n The queue elements are:\n ");
for(i=front;i<=rear;i++)
{
printf("\t %d",queue[i]);
}
}
}
Check this code its working fine.
Few suggestions don't use conio.h [clrscr(), and getch()] these are not standards.
Try the code below it worked for me fine.
CODE
#include<stdio.h>
#define SIZE 5
int front = -1;
int rear = -1;
int queue[SIZE];
void enqueue(int item);
int dequeue();
void display();
int main()
{
int item, choice, cont = 1;
while(cont == 1)
{
printf("\n1.Enqueue into queue.\n");
printf("\n2.Dequeue from queue.\n");
printf("\n3.display quesue elements\n");
printf("\nEnter your choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nEnter the value of item: ");
scanf("%d",&item);
enqueue(item);
break;
case 2:
item = dequeue();
if(item != NULL)
{
printf("\nItem dequeued: %d\n",item);
}
break;
case 3:
display();
break;
default:
printf("\nInvalid choice.\n");
break;
}
printf("\nDo you want to continue (1/0): ");
scanf("%d",&cont);
}
printf("");
return 0;
}
void enqueue(int item)
{
if(front==0 && rear==SIZE-1)
printf("\n Queue OverFlow Occured");
else if(front==-1 && rear==-1)
{
front=rear=0;
queue[rear]=item;
}
else if(rear==SIZE-1 && front!=0)
{
rear=0;
queue[rear]=item;
}
else
{
rear++;
queue[rear]=item;
}
}
int dequeue()
{
int item = NULL;
if(front == -1 && rear == -1)
{
printf("\nQueue is empty. Dequeue not possible.\n");
}
else
{
item = queue[front];
queue[front] = NULL;
if(front == rear)
{
front = -1;
rear = -1;
}
else
{
front = front + 1;
}
}
return(item);
}
void display()
{
int i;
if(front==-1)
printf("\n No elements to display");
else
{
printf("\n The queue elements are:\n ");
for(i=front;i<=rear;i++)
{
printf("\t %d",queue[i]);
}
}
}
OUTPUT
Do you want to continue (1/0): 1
1.Enqueue into queue.
2.Dequeue from queue.
3.display quesue elements
Enter your choice: 3
The queue elements are:
5 5
Do you want to continue (1/0): 1
1.Enqueue into queue.
2.Dequeue from queue.
3.display quesue elements
Enter your choice: 1
Enter the value of item: 43
Do you want to continue (1/0): 1
1.Enqueue into queue.
2.Dequeue from queue.
3.display quesue elements
Enter your choice: 3
The queue elements are:
5 5 43
Do you want to continue (1/0): 1
1.Enqueue into queue.
2.Dequeue from queue.
3.display quesue elements
Enter your choice: 2
Item dequeued: 5
Do you want to continue (1/0): 1
1.Enqueue into queue.
2.Dequeue from queue.
3.display quesue elements
Enter your choice: 3
The queue elements are:
5 43
Do you want to continue (1/0):
Thats a rather confusing code. Since the idea is for the queue to be circular, trying to determine if the queue is full by checking the position of front and rear can be really tricky, aswell as trying to make decisions based on front being higher than rear etc. You can avoid all that. A third variable keeping track of the length of the queue will make your life a whole lot easier.
Try this implementation instead:
#define SIZE 5
int queue[SIZE];
int read = 0, write = 0, size = 0;
void enqueue(int item)
{
if (size >= SIZE)
{
printf("Queue is full");
return;
}
queue[write] = item;
write = (write + 1) % SIZE;
size++;
}
int dequeue()
{
if (size == 0)
{
printf("Queue is empty");
return 0;
}
read %= SIZE;
size--;
return queue[read++];
}
Here is your Fully Functional updated code. I pasted code on Ideone.com Link is link to code
If you don't understand anything just ask. I tried to explain it using comments. And now it is not having any problem that you were facing .
#include<stdio.h>
#include<conio.h>
#define SIZE 5
int front = -1;
int rear = -1;
int queue[SIZE];
void enqueue(int item);
int dequeue();
void display();
void main()
{
int item, choice, cont = 1;
clrscr();
while(cont == 1)
{
printf("\n1.Enqueue into queue.\n");
printf("\n2.Dequeue from queue.\n");
printf("\n3.display quesue elements\n");
printf("\nEnter your choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nEnter the value of item: ");
scanf("%d",&item);
enqueue(item);
break;
case 2:
item = dequeue();
if(item != NULL)
{
printf("\nItem dequeued: %d\n",item);
}
break;
case 3:
display();
break;
default:
printf("\nInvalid choice.\n");
break;
}
printf("\nDo you want to continue (1/0): ");
scanf("%d",&cont);
}
getch();
}
void enqueue(int item)
{
int temp = (rear+1)%SIZE; //EDIT HERE
if(temp == front){
printf("\n Queue OverFlow Occured");
return;
}
else if(front==-1 )
{
front=rear=0;
queue[rear]=item;
return;
}
else{
rear = (rear+1)%SIZE; // EDIT HERE
queue[rear%SIZE]=item;
}
}
int dequeue()
{
int item = NULL;
if(front == rear) // modified condition
{
printf("\nQueue is empty. Dequeue not possible.\n");
}
else
{
item = queue[front];
queue[front] = NULL;
front++; // front must be incremented
if(front > rear)
{
front = -1;
rear = -1;
}
}
return(item);
}
void display()
{
int i;
if(front==-1)
printf("\n No elements to display");
else
{
printf("\n The queue elements are:\n ");
for(i=front;i<=rear;i++)
{
printf("%d\t",queue[i]);
}
}
}

Static stack operations in C

i'm trying to perform all operations(push, pop, peep, update, show) on stack using array in C.It's working fine when i am calling the show() at last after calling all of the functions that i need. But whenever i call show() before any of the operations than it is not giving me the appropiate result.
I'm using following code:
int main()
{
push(1);
push(2);
push(3);
push(4);
push(6);
pop();
push(5);
show();//line 8
//push(7);//line 9
//pop();
//peep();
//update();
//show();//line 13
return;
}
void push(int num){//insert an item
if(top==MAXSIZE-1)
{
printf("Overflow condition");
return;
}
top++;
stack[top]=num;
//return;
}
void pop()//delete a item from top
{
int num;
if(top==-1)
{
printf("Underflow condition");
return;
}
num=stack[top];
top--;
//return;
}
void show()//display elements
{
if(top==-1){
printf("Underflow");
return;
}
while(top!=-1){
printf("%d\n",stack[top--]);
}
//return;
}
void peep()//extract information
{
int loc,num;
printf("enter location:\n");
scanf("%d",&loc);
if(top-loc+1 < 0)
{
printf("No item at the given location\n");
return;
}
else{
num=stack[top-loc+1];
printf("\nItem at location %d is %d",loc,num);
}
}
void update(){//update information
int loc,item;
printf("enter new item:");
scanf("%d",&item);
printf("enter location:");
scanf("%d",&loc);
if(top-loc+1 < 0)
{
printf("No item at the given location\n");
return;
}
else{
stack[top-loc+1]=item;
printf("\nItem inserted");
}
}
Here after calling show(),top will point to -1(empty) at line 8,so after that following consequences will be:
push() will insert at position 1 instead of at top.
pop() will show underflow condition.
peep() and update will go in if condition.
So how can i set top to the top element in the stack after once calling the show()?
Thanks.
Your show() method modifies the top pointer and this is wrong:
void show()//display elements
{
if(top==-1){
printf("Underflow");
return;
}
while(top!=-1){
printf("%d\n",stack[top--]); // <--- here 'top--' will modify the top pointer
}
//return;
}
You can change the show() method like this:
void show()//display elements
{
if(top==-1){
printf("Underflow");
return;
}
int i = top; // introducing a new variable to iterate through the stack
while(i!=-1){
printf("%d\n",stack[i--]); // now 'i' is modified
}
//return;
}
One problem with your show function is that, it is also trying to pop out all the data. You should not be doing the top-- in your show function.
//WAP to perform Stack Operation usin C--
1. Push, 2.pop, 3.peep, 4.change, 5.top-of-stack, 6.is-empty, 7.is-full, 8.display
#include<stdlib.h>
#include<stdio.h>
#define max_size 5
int stack[max_size],top=-1,i,x;
/*------ Function Prototype------------*/
void push();
void pop();
void peep();
void display();
void top_stack();
void change();
void is_empty();
/*-------------------------------------*/
int main()
{
int choice;
do{
printf("\n\n--------STACK OPERATIONS-----------\n");
printf("1.Push\n");
printf("2.Pop\n");
printf("3.Peep\n");
printf("4.Display\n");
printf("5.Change\n");
printf("6.TOP\n");
printf("7.exit\n");
printf("-----------------------");
printf("\nEnter your choice:\t");
scanf("%d",&choice);
switch(choice)
{
case 1: push();
break;
case 2: pop();
break;
case 3: peep();
break;
case 4: display();
break;
case 5: change();
break;
case 6: top_stack();
break;
case 7: exit(0);
break;
default: printf("\nInvalid choice:\n");
break;
}
}while(choice!=7);
return 0;
}
void push() //Inserting element in to the stack
{
int item;
if(top==(max_size-1))
{
printf("\nStack Overflow:");
}
else
{
printf("Enter the element to be inserted:\t");
scanf("%d",&item);
top=top+1;
stack[top]=item;
}
}
void pop() //deleting an element from the stack
{
int item;
if(top==-1)
{
printf("Stack Underflow:");
}
else
{
item=stack[top];
top=top-1;
printf("\nThe poped element: %d\t",item);
}
}
void peep()
{
printf("enter the i th element");
scanf("%d",&i);
if(top-i+1<0)
{
printf("\nStack is empty:");
}
else
{
printf("The topmost element of the stack is %d",stack[top-i+1]);
}
}
void display()
{
int i;
if(top==-1)
{
printf("\nStack is Empty:");
}
else
{
printf("\nThe stack elements are:\n" );
for(i=top;i>=0;i--)
{
printf("%d\n",stack[i]);
}
}
}
void change()
{
printf("enter the i th element");
scanf("%d",&i);
if(top-i+1<0)
{
printf("\nStack is empty:");
}
else
{
printf("enter the element to be changed\n");
scanf("%d",&x);
stack[top-i+1]=x ;
printf("The topmost element of the stack is %d",stack[top-i+1]);
}
}
void top_stack()
{
int t;
t=stack[top];
printf("The Topmost element of stack is =%d",t);
}

Stack of strings

Hi i have program here that accept int as value. i wanted to translate it to accept strings in array then. i have read about using struct but i couldnt get into it. i hope someone can help me getting into that without using struct i dont know where to start i want to keep this lines of code.
#include <stdio.h>
#include <ctype.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>
int top = 0;
int *stack = NULL;
int size = 0;
main()
{
int opt, num;
char cont[] = { 'y' };
clrscr();
/* <start Declaring Stack Size { */
printf("Stacking Program");
printf("\n\nData Size: ");
scanf("%d", &size);
printf("\n");
/* } end> */
/* <start Allocates size of stack { */
if(size > 0)
{
stack = malloc(size * sizeof(int));
if(stack == NULL)
{
printf("ERROR: malloc() failed\n");
exit(2);
}
}
else
{
printf("ERROR: size should be positive integer\n");
exit(1);
}
/* } end> */
while((cont[0] == 'y') || (cont[0] == 'Y'))
{
clrscr();
/* <start Main Menu { */
printf("Stacking Program");
printf("\n\nData Size: %d\n\n", size);
printf("MAIN MENU\n1. Pop\n2. Push\n3. Pick\n4. View\nChoose: ");
scanf("%d", &opt);
printf("\n");
switch(opt) {
case 1:
pop();
break;
case 2:
if(top==size)
{
printf("You can't push more data");
}
else
{
printf("Enter data for Stack[%d]: ", top+1);
scanf("%d", &num);
push(num);
}
break;
case 3:
pick();
break;
case 4:
view();
break;
default:
printf("Your choice is not on the list.");
break;
}
/* } end> */
printf("\n\nDo you want continue\(Y\/N\)?");
scanf("%s", &cont[0]);
}
free(stack);
}
pop()
{
int a;
loading();
if(top <= 0)
{
printf("Stack empty.");
return 0;
}
else
{
top--;
a=stack[top];
printf("\(Stack[%d] = %d\) removed.", top+1, a);
}
}
push(int a)
{
stack[top]=a;
top++;
loading();
}
pick()
{
loading();
if(top <= 0)
{
printf("Nothing to display.");
return 0;
}
else
{
printf("\(Stack[%d] = %d\) is the last data.", top, stack[top-1]);
}
}
view()
{
int i;
loading();
if(top <= 0)
{
printf("Nothing to display.");
return 0;
}
else
{
for(i=0;i<top;i++)
{
printf("Stack[%d] = %d\n", i+1, stack[i]);
}
}
}
loading()
{
float i, x;
float load;
int loadarea[] = { 5000, 10000, 15000, 20000, 25000, 30000 };
int percentLoad;
x=0;
load=0;
percentLoad = loadarea[random(5)];
gotoxy(26,11);
printf("[");
for(i=0;i<25;i++)
{
x = i+27;
gotoxy(x, 11);
printf("=");
delay(percentLoad);
gotoxy(51,11);
printf("]");
gotoxy(53,11);
load=(i/25)*104.5;
if(load>100)
load = 100.00;
printf("%.2f\%",load);
}
delay(60000);
for(i=0;i<60;i++) {
printf("\b \b");
}
printf("\n");
}
Easiest way is to convert your stack to store char* instead of int.
char **stack;
stack = malloc( size * sizeof(char*) );
Now, your push operation will accept a char* from some buffer that is storing the string that was just input, duplicate it with strdup, and store that new pointer in the stack.
typedef enum {
STACK_MEM_ERROR = -1,
STACK_FULL = 0,
STACK_OK = 1
} StackStatus;
StackStatus push(const char *str)
{
char *newstr;
if( top >= size ) return STACK_FULL;
newstr = strdup(str);
if( newstr == NULL ) return STACK_MEM_ERROR;
stack[top++] = newstr;
return STACK_OK;
}
When you pop a string, you just get a pointer.
char *pop()
{
if( top == 0 ) return NULL;
return stack[--top];
}
You are responsible for freeing that memory when you are finished with the pointer (by calling free).
char * val;
while( NULL != (val = pop()) )
{
printf( "I popped: %s\n", val );
free(val);
}

Resources