stack not getting updated after performing operations - arrays

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.

Related

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.

push operation fails in c stack data structure

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.

What is wrong with my program implementing a stack in C

Hi i have a problem with my stack data structure program. It seems that when i define the size of my array/the imaginary size of array just to call it through a loop the size i defined or specified by the user is being depleted or somewhat edited when i enter a data or push.
For ex. i entered 5 for the size and choose push and then add 2. It is working properly. But if i choose to push data again, it is now passing to the size variable. I do not know understand what is happening...
#include <stdio.h>
#include <ctype.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>
#define p printf
#define s scanf
int top;
int ar[1];
int size;
main()
{
void push();
int opt, num;
char cont[] = { 'y' };
clrscr();
p("Stacking Program");
p("\n\nData Size: ");
s("%d", &size);
p("\n");
while((cont[0] == 'y') || (cont[0] == 'Y'))
{
clrscr();
p("Stacking Program");
p("\n\nData Size: %d\n\n", size);
p("MAIN MENU\n1. Pop\n2. Push\n3. Pick\n4. View\nChoose: ");
s("%d", &opt);
p("\n");
switch(opt) {
case 1:
pop();
break;
case 2:
if(top > size)
{
p("You can't push more data");
}
else
{
p("Enter data for Data[%d]: ", top);
s("%d", &num);
push(num);
}
break;
case 3:
pick();
break;
case 4:
view();
break;
default:
p("Your choice is not in the list.");
break;
}
p("\n\nDo you want continue\(Y\/N\)?");
s("%s", &cont[0]);
}
}
pop()
{
int a;
if(top < 0)
{
p("Stack empty.");
return 0;
}
else
{
a = ar[top];
p("\(Data[%d] = %d\) removed.", top, a);
top--;
}
}
void push(int b)
{
top++;
ar[top] = b;
}
pick()
{
if(top < 0)
{
p("Nothing to display.");
return 0;
}
else
{
p("\(Data[%d] = %d\) is the last data.", top, ar[top]);
}
}
view()
{
int i;
if(top < 0)
{
p("Nothing to display.");
return 0;
}
else
{
for(i = 1; i < (top + 1); i++)
{
p("Data[%d] = %d\n", i, ar[i]);
}
}
}
You need to define the size of the array at runtime, using the size entered by the user.
instead of:
int top;
int ar[1];
int size;
...
int top = -1;
int *ar = NULL;
int size = 0;
and then after getting size from the user:
if ( size > 0 )
{
ar = malloc(size * sizeof(int));
if ( ar == NULL )
{
printf("ERROR: malloc() failed\n");
exit(2);
}
}
else
{
printf("ERROR: size should be positive integer\n");
exit(1);
}
....
p("\n\nDo you want continue(Y/N)?");
s("%s", &cont[0]);
}
free(ar);
} // end of main
I think the for loop in view() should be:
for(i = 0 ; i <= top ; i++)
also
case 2:
if ( top == ( size - 1 ))
If you don't want to dynamically size the array, another approach is to allocate an array with MAXSIZE elements, where MAXSIZE is "big enough". Also, some other comments:
You declared at the top of your program a character array of size 1:
char cont[] = { 'y' };
But in your scanf line later you try to use this:
s("%s", &cont[0]);
This will overflow your buffer even if the user types just one character, because %s assumes that the buffer has at least two bytes available, one for the character and one for the '\0'. Possible fix:
char cont[] = { 'y', '\0' };
// ...
s("%1s", cont);
Note that cont is the same and more common way of saying &cont[0].
Another problem is with things that might be caught by the compiler if warnings are turned on: all functions should be prototyped before they are mentioned, functions without explicit return type should be declared with type int, and you should not let a function drop off without returning a value even though you declared it to explicitly or implicitly. Also, '(' and ')' do not need to be escaped in string literals.
Here is a modified version with changes noted. I have redefined clrscr() because I don't have conio.h on this system:
#include <stdio.h>
#include <ctype.h>
// #include <conio.h>
#define clrscr() printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n")
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#define p printf
#define s scanf
#define MAXSIZE 500
// prototypes [Changed]
int pop();
void push(int b);
int pick();
int view();
int top;
int ar[MAXSIZE];
int size;
int main()
{
int opt, num;
char cont[] = { 'y', '\0' }; // [Changed]
clrscr();
p("Stacking Program\n\n");
// keep asking until we get a valid size [Changed]
for (;;)
{
p("Data Size: ");
s("%d", &size);
if (size > 0 && size < MAXSIZE)
break;
printf("Not a valid size!\n");
}
p("\n");
while((cont[0] == 'y') || (cont[0] == 'Y'))
{
clrscr();
p("Stacking Program");
p("\n\nData Size: %d\n\n", size);
p("MAIN MENU\n1. Pop\n2. Push\n3. Pick\n4. View\nChoose: ");
s("%d", &opt);
p("\n");
switch(opt) {
case 1:
pop();
break;
case 2:
if(top > size)
{
p("You can't push more data");
}
else
{
p("Enter data for Data[%d]: ", top);
s("%d", &num);
push(num);
}
break;
case 3:
pick();
break;
case 4:
view();
break;
default:
p("Your choice is not in the list.");
break;
}
p("\n\nDo you want continue(Y/N)?");
s("%1s", cont); // [Changed]
}
return 0;
}
int pop()
{
int a;
if(top == 0) // [Changed]
{
p("Stack empty.");
return 0;
}
else
{
top--; // [Changed]
a = ar[top];
p("(Data[%d] = %d) removed.", top, a);
return a; // [Changed]
}
}
void push(int b)
{
ar[top] = b;
top++; // [Changed]
}
int pick()
{
if(top == 0) // [Changed]
{
p("Nothing to display.");
return 0;
}
else
{
p("(Data[%d] = %d) is the last data.", top, ar[top-1]); // [Changed]
return -1; // [Changed]
}
}
int view()
{
int i;
if(top < 0)
{
p("Nothing to display.");
return 0;
}
else
{
for(i = 0; i < top; i++) // [Changed]
{
p("Data[%d] = %d\n", i, ar[i]);
}
return -1; // [Changed]
}
}

Resources