push operation fails in c stack data structure - c

Hello everyone i got some issues here with the following code actually the code compiles successfully but when i called the display function it outputs one's instead of the actual content of the stack. can anyone explains to me what wrong with the display function.
thank you
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 10
int stack[MAXSIZE];
int top = -1;
int menu();
void push();
void pop();
void peep();
void display();
void main() {
char ch;
int item;
do{
switch(menu()) {
case 1:
push();
break;
case 2:
pop();
break;
case 3:
peep();
break;
case 4:
display();
default:
printf("Invalid choice try again\n");
break;
}
printf("Do you want to continue ? (Y/N): ");
printf("top value is %d", top);
fflush(stdin);
scanf("%c", &ch);
}while(ch == 'Y' || ch == 'y');
}
int menu() {
int choice;
printf("Welcome to stack program \n\n");
printf("\n #1. push");
printf("\n #2. pop");
printf("\n #3. peep");
printf("\n #4. display");
printf("\nchoice: ");
scanf("%d", &choice);
return choice;
}
void push() {
int item;
printf("Enter element to add to stack: ");
item = scanf("%d", &item);
if(top == MAXSIZE - 1) {
printf("stack overflow can't add any more item\n");
exit(0);
} else {
top++;
stack[top] = item;
}
}
void pop() {
if(top == -1) {
printf("stack underflow deletion not possible\n");
exit(0);
} else {
printf("Element %d is deleted from the stack\n", stack[top]);
top--;
}
}
void peep() {
int i;
int element;
printf("Enter the location that you want to peep");
fflush(stdin);
scanf("%d", &i);
if(top - i + 1 < 0) {
printf("Location not valid");
exit(0);
} else {
element = stack[top - i + 1];
printf("The location %d contains the element %d \n", i, element);
}
}
void display() {
if(top != -1){
int j;
printf("Elements in the stack\n");
for(j = top; j >= 0; j--) {
printf("%d\n", stack[j]);
}
} else {
printf("Stack is empty\n");
}
}

Specific issues: missing break statement on case 4:; inconsistent use of fflush(stdin) when fpurge(stdin) seems to make more sense; using success exit code on failure and printing fatal errors to stdout instead of stderr; not clear what location in peep() represents relative to stack, should be documented;
I didn't like your basic design (all stack operations have void return value and no arguments) so I redid it such that the stack operations are functional and the I/O to get values into or out of them is handled external to the routines in the switch statement in main:
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 10
int stack[MAXSIZE];
int top = -1;
int menu();
void push(int item);
int pop();
int peep(int location);
void display();
int main() {
char ch = 'Y';
int temporary;
while (ch == 'Y' || ch == 'y') {
switch(menu()) {
case 1:
printf("Enter element to add to stack: ");
(void) scanf("%d", &temporary);
(void) fpurge(stdin);
push(temporary);
break;
case 2:
temporary = pop();
printf("Element %d is deleted from the stack\n", temporary);
break;
case 3:
printf("Enter the location that you want to peep: ");
(void) scanf("%d", &temporary);
(void) fpurge(stdin);
printf("The location %d ", temporary);
temporary = peep(temporary);
printf("contains the element %d\n", temporary);
break;
case 4:
display();
break;
default:
printf("Invalid choice try again\n");
break;
}
printf("Value of 'top' is %d\n", top);
printf("Do you want to continue? (Y/N): ");
(void) scanf("%c", &ch);
(void) fpurge(stdin);
}
return EXIT_SUCCESS;
}
int menu() {
int choice;
printf("Welcome to stack program\n");
printf("\n #1. push");
printf("\n #2. pop");
printf("\n #3. peep");
printf("\n #4. display");
printf("\nchoice: ");
(void) scanf("%d", &choice);
(void) fpurge(stdin);
return choice;
}
void push(int item) {
if (top + 1 == MAXSIZE) {
fprintf(stderr, "stack overflow can't add any more item\n");
exit(EXIT_FAILURE);
}
stack[++top] = item;
}
int pop() {
if (top == -1) {
fprintf(stderr, "stack underflow deletion not possible\n");
exit(EXIT_FAILURE);
}
return stack[top--];
}
int peep(int location) {
if (top - location + 1 < 0) {
fprintf(stderr, "Location not valid");
exit(EXIT_FAILURE);
}
int element = stack[top - location + 1];
return element;
}
void display() {
if (top != -1) {
printf("Elements in the stack\n");
for (int j = top; j > -1; j--) {
printf("%d\n", stack[j]);
}
} else {
printf("Stack is empty\n");
}
}
Lots more error checking can, and should be done, this is not finished code.

Related

stack not getting updated after performing operations

I m trying to implement stack using array and performing basic operations on it. All my operations are performing well. But the issue is when i again try to do the same operation, it seems like they are begin performed on the same old stack and not the updated one after the performing the operations.
for e.g when i push an element in the stack and then try to display the stack , it doesn't display's the pushed element. The same happens with pop() as well every time it shows the same element begin popped out.
Here's my C code for stack:
#include <stdio.h>
#define MAXSIZE 15
int stack[MAXSIZE];
int top = -1;
void push(int x)
{
if (top == MAXSIZE - 1)
{
printf("Overflow Condition");
}
else
{
top++;
stack[top] = x;
}
}
void pop()
{
int item;
if (top == -1)
{
printf("Underflow Condition\n");
}
else
{
item = stack[top];
top--;
printf("The popped element is: %d", item);
}
}
void peek()
{
if (top == -1)
{
printf("Underflow Condition\n");
}
else
{
printf("%d", stack[top]);
}
}
void displayStack()
{
int i;
for (i = top; i >= 0; i--)
{
printf("%d ", stack[top]);
top--;
}
}
int main()
{
// Push the starting element:
push(2);
push(3);
push(4);
push(5);
push(6);
int ch, a;
printf("Enter Choice: \n 1: push\n 2: pop\n 3: peek\n 4: display \n\n");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("Enter the element you want to push to stack: ");
scanf("%d", &a);
push(a);
break;
case 2:
pop();
break;
case 3:
peek();
break;
case 4:
displayStack();
break;
default:
printf("Invalid Choice...");
}
}
Any idea what's the matter??
Try to replace your displayStack() function with this:
void displayStack()
{
int i;
for (i = top; i >= 0; i--)
{
printf("%d ", stack[i]);
}
}
You should not modify a data structure inside an output function. Everything else seems fine.

C program How to get return value from other function by using switch statement

So I am trying to do a program where it shows a menu and asks what will the user do. I am stuck in where I cant get the return value in case 1 and use it in case 5. I am only a beginner and need help.
This is what I have in my program.
#include <stdio.h>
int choice, arrayval, val;
char reply, y, n;
void menu()
{
printf("\n\n");
printf("MAIN MENU");
printf("\n\n");
printf("[1] - Store/Fill Array\n");
printf("[2] - Find and Replace\n");
printf("[3] - Display Frequency\n");
printf("[4] - Unique\n");
printf("[5] - Print\n");
printf("[0] - Print\n");
printf("Enter your choice: ");
scanf(" %s", &choice);
}
int storearray()
{
int arrayval[10];
int i;
for(i=0;i<10;i++)
{
printf("Enter Value for Array[%d]", i);
scanf("%d", &arrayval[i]);
}
return arrayval;
}
void printarr(arrayval)
{
int i;
for(i=0;i<10;i++)
{
printf("Array[%d] %d\n", i, arrayval);
}
}
int main()
{
do
{
menu();
switch(choice)
{
case '1':
storearray();
main();
break;
case '5':
val = storearray();
printarr(val);
return 0;
break;
default:
printf("Invalid");
}
}
while (choice != 1,2,3,4,5);
printf("End of Program!");
return 0;
}
need help on how to get the value from storearray() and use it to print in printarr()
Here's a modified version of your code with the fixes mentioned in the comments of your question:
#include <stdio.h>
#include<stdlib.h>
char choice;
int *val;
char reply, y, n;
void menu()
{
printf("\n\n");
printf("MAIN MENU");
printf("\n\n");
printf("[1] - Store/Fill Array\n");
printf("[2] - Find and Replace\n");
printf("[3] - Display Frequency\n");
printf("[4] - Unique\n");
printf("[5] - Print\n");
printf("[0] - Print\n");
printf("Enter your choice: ");
scanf(" %c", &choice);
}
int* storearray()
{
int *arrayval=malloc(10*sizeof(int));
int i;
for (i = 0; i < 10; i++)
{
printf("Enter Value for Array[%d]", i);
scanf("%d", &arrayval[i]);
}
return arrayval;
}
void printarr(int *arrayval)
{
int i;
for (i = 0; i < 10; i++)
{
printf("Array[%d] %d\n", i, arrayval[i]);
}
}
int main(void){
val=NULL;
int inv=1;
do
{
menu();
switch (choice)
{
case '1':
val=storearray(); //be sure to `free(val)` (if `val` is pointing to a malloc'ed memory) before you do `val=storearray()` or you'll lose the pointer and it'll result in a memory leak
break;
case '5':
//I'd also recommend a check here to ensure `val` isn't NULL
printarr(val);
inv=0;
break;
default:
printf("Invalid");
inv=0;
break;
}
} while (inv);
printf("End of Program!");
free(val);
return 0;
}
Also, as chux mentioned in the comment:
"I am only a beginner and need help." --> Simple tip: enable all compiler warnings. Faster feedback than posting stack overflow.

Segmentation fault in C for Stack implementation using arrays with pointers

I have this code for stack implementation using arrays with pointers which performs lot of operations like push, peep, pop, destroy.
I already done this by declaring globally Stack and Stacktop that time it worked but now I am want to use pointer for this implementation , so here is my code :
#include <stdio.h>
int Full(int Stack[], int *StackTop, int *StackSize){
if (*StackTop == *StackSize-1){
return 1 ;
}
else{
return 0;
}
}
int Empty(int Stack[], int *StackTop){
if (*StackTop == -1){
return 1 ;
}
else{
return 0;
}
}
void PushStack(int ele, int Stack[], int *StackTop, int *StackSize){
if (!Full(Stack, &StackTop, &StackSize)){
Stack[++(*StackTop)]= ele ;
}
else{
printf("Error: Stack is full");
}
}
int PopStack(int Stack[], int *StackTop){
if(!Empty(Stack, &StackTop)){
printf("%d popped !",Stack[*StackTop--]);
}
else{
printf("Error : Stack is Empty");
}
}
void PeepStack(int Stack[], int *StackTop){
if(!Empty(Stack, &StackTop)){
printf("%d", Stack[*StackTop]) ;
}
else{
printf("Error : Stack is Empty");
}
}
int DestroyStack(int Stack[], int *StackTop){
printf("Destroying Stack\n");
if (!Empty(Stack, &StackTop)){
while(!Empty(Stack, &StackTop)){
PopStack(Stack, &StackTop);
printf("\n");
}
}
else{
printf("Stack is already Empty");
}
}
int DisplayStack(int Stack[], int *StackTop){
int i ;
if(Empty(Stack, &StackTop)){
printf("Stack is Empty");
}
else{
printf("Displaying Stack ....\n");
for(i=StackTop; i>=0; --i){
printf("| %d |\n",Stack[i]);
}
}
}
int main(void) {
int StackSize = 5 ;
int Stack[5] ;
int StackTop = -1 ;
int *Top = &StackTop ;
int *Size = &StackSize ;
while(1){
int option, ele ;
printf("\n Options : \n");
printf("1. Push \n");
printf("2. Pop \n");
printf("3. Peep \n");
printf("4. Destroy \n");
printf("5. Display \n");
printf("6. Exit \n");
printf("Enter Option number : ");
scanf("%d", &option);
switch(option){
case 1 :
printf("Enter element you want to push : ");
scanf("%d", &ele);
PushStack(ele,&Stack,&Top, &Size);
break;
case 2 :
PopStack(Stack, &Top);
break;
case 3 :
PeepStack(Stack, &Top);
break;
case 4 :
DestroyStack(Stack, &Top);
printf("Stack Destroyed succesfully !");
break ;
case 5 :
DisplayStack(Stack, &Top);
break;
case 6 :
break ;
default:
printf("Invalid option");
}
printf("\n");
if(option==6){
break;
}
}
return 0;
}
When I execute this on repl.it, I am able to give first input i.e. option number but then it gives me a segmentation fault but when I execute this on codeblocks, I get process returned with some numbers and one hexadecimal code.
So what's wrong in this code ?
because of which line I am getting this error ?
You're using the & operator on a pointer, which makes is a pointer to a pointer.
Basically the pattern you have is this:
void Foo(int *bar)
{
*bar = 123;
}
int main()
{
int thing;
int *p = &thing; // p points to thing
Foo(&p);
printf("%d", &p); // your expected output is: 123
}
But instead of:
Foo(&p);
you want:
Foo(p);
Because p is already a pointer.
But if you want to use thing you need to write:
Foo(&thing);
because &thing points to thing just as p points to thing.

Having trouble displaying the contents of my array stack

So I am learning how stack works in C, and I wrote out a little menu that allows the user to push and pop integers to and from the stack. I used the global array implementation of stack.
#include <stdio.h>
#define MAX 5
int top = -1;
int myStack[MAX];
int push(int item){
if(top >= MAX - 1){
printf("stack overflow");
return -999;
}
else{
top++;
myStack[top] = item;
}
return 1;
}
int pop(){
if(top == -1){
printf("no integer to pop from stack.");
return -999;
}
int popped = myStack[top];
top--;
return popped;
}
void displayStack(int myStack[], int top){
for(int i = 0; i < top; i ++){
printf("%d ", myStack[i]);
}
}
int main(){
printf("Menu Options:\n");
printf("1 - Push\n");
printf("2 - Pop\n\n");
int data, choice;
while(1){
printf("Enter choice: ");
scanf("%d", &choice);
if(choice == 1){
printf("Enter data to push: ");
scanf("%d", &data);
push(data);
displayStack(myStack, top);
printf("\n\n");
}
if(choice == 2){
pop();
displayStack(myStack, top);
printf("\n\n");
}
if(choice == 3){
break;
}
}
return 0;
}
My problem is, when I run the code for the first time and insert 1 to push an integer to the stack, everytime, the first call to push, my display doesn't return anything. Only the second time will it display an item from the stack on the screen.
I think this has something to do with the indexes in my display function, but I'm pretty sure I have them correct? After I call push, the top of the stack for the first time goes from -1 to 0, and my displayStack function is starting at index 0.
Any help would be appreciated, thank you!

Some trouble with c code

When I choose push in my menu, then I enter some number value, then the program works fine, but when I enter some letter value, then program never stops, where is my mistake?
I'm beginner in c, so maybe someone can help solve this problem.
I have this code:
#include <stdio.h>
#include <curses.h>
int a[15], top = -1;
void push (int value)
{
if (top == 14)
{
printf("Stack is full");
}
else{
top = top + 1;
a[top] = value;
}
}
void pop()
{
if (top == -1)
{
printf("Stack is empty");
}
else
{
top = top - 1;
}
}
void display()
{
int i;
if (top == -1)
{
printf("\n Nothing to display");
}
else
{
printf("\nArray is:\n");
for (i=0; i<=top; i++)
{
printf("%d\n", a[i]);
}
}
}
int main()
{
int choice, value;
do{
printf("\n1.Push :");
printf("\n2.POP :");
printf("\n3.Display :");
printf("\n4.Exit :");
printf("\nEnter your Choice:");
scanf("%d", &choice);
if(choice == 1)
{
printf("\nEnter Value to be inserted: ");
scanf("%d", &value);
push(value);
}
if(choice == 2)
{
pop();
}
if (choice == 3)
{
display();
}
}
while (choice !=4);
getch();
return 0;
}
You need to change two things for your code to work.First change the following variables to character
char a[15];
char value;
plus you also need to pass a charater to the function not an integer.

Resources