Dynamic Allocation Vs Static Allocation: Case Study-[Stack]
/*Do Not directly paste the code-They are just abstract implementations(IO/Extra variable declarations are missing) */
/*Task for you after reading this: Implement stack using Linked List*/
Implement a stack using array.
Logic and Data Structure: I need an array with a predefined size (say 10). Functions: Push(),Pop() and display().
While Calling these functions: Pass the array as an argument.
#include
/*Push Function*/ void push (int stack[], int item) { if (top == (MAX-1)) status = 0; else { status = 1; ++top; stack [top] = item; } }
/*Pop Function*/ int pop (int stack[]) { int ret; if (top == -1) { ret = 0; status = 0; } else { status = 1; ret = stack [top]; --top; } return ret; } int main() { int stack [MAX], item; if (push) { Checkoverflow condition push (stack,item); Passing the array as an argument. /*Question for you- Will this pass an array to the pointer or the array itself?*/ } If (pop) { Check the underflow condition Else Pop(stack); }
}
Implement a stack using array: Structures
The issue with above given implementation- Every time (passing the array or pointer to the array?) as an argument. How about Using a STRUCTURE and access it via a variable instance in every function.
Also How about declaring multiple stacks?.
So I need a different array variable for every stack! Different top variables for every stack declared.
Too many variables!! Better way: I declare a STRUCTURE for a STACK with array and a top variable as its members. Create instances (objects) of that STRUCTURE. Using an instance I can initialize a stack and probably multiple stacks by using multiple instances.
#include
Implement a stack using array: Dynamic Allocation
So, I want my stack to work on arbitrary array length (to be given by user). DYNAMIC MEMORY- i.e allocate memory at runtime. #include
} else { int iter; printf("your stack is"); for (iter=0;iter<=s->top;iter++) { int number = s->a[iter]; printf("%d",number); //return 0; } } } int main()
{ struct stack *st = (struct stack*)malloc(sizeof(struct stack)); /*Allocate memory to structure pointer why? */ st->top = -1; int m; printf("Enter the size of array stack");/*User can declare the size of array*/ scanf("%d",&m); st->size= m; st->a= (int*)malloc(sizeof(int)*m); /* Dynamic memory allocation of the array to be used as a stack */ int h; int k = 50; char op[1000]; while(k--) { printf("Enter operation"); scanf("%s",op); if(strcmp(op,"push")==0) { int num; printf("Enter the number"); scanf("%d",&num); printf("%d\n",push(st,num)); } else if(strcmp(op,"pop")==0) { printf("%d\n",pop(st)); } else if(strcmp(op,"isempty")==0) { printf("%d",isempty(st)); } else if(strcmp(op,"display")==0) { display(st); } }}