enter code here
i was watching a video in data structures in C , and when i understand the abstract view of the concept i go try implementing it without watching the implementation in the video , and what i implement wasn't in the video, the video was affording stack(static array and linked list). so i thought maybe i try my own that is using (dynamic array), and the program did work but i'm still in doubt if it 100% work without any side effect .it's just that i can't believe the program works.
this program is intended to solve the overflow when pushing new value in the stack and without wasting memory space
(my doubts are : if it reallocate memory each time i push a new value correctly )
#include<stdio.h>
#include<stdlib.h>
int *ptr;
int top = -1;
int size = sizeof(int) ;
void Push(int x);
void Pop();
int Top();
char isEmpty();
int main(){
Push(1);
Push(2);
printf("%d\n", *(ptr+top));
Pop();
printf("%d\n", *(ptr+top));
printf("top = %d, is empty : %c", Top(), isEmpty());
return 0;
}
void Push(int x){
if(top == -1){
ptr = (int* )malloc(size);
*ptr = x;
top++;
}
else{
realloc(ptr, size * (top + 1));
*(ptr+top+1) = x;
top++;
}
}
void Pop(){
if(top == -1){
return;
}
free(ptr+top);
realloc(ptr, size * top - 1);
top--;
}
int Top(){
if(top != -1){
return *(ptr+top);
}
printf("Empty Stack\n");
return 0;
}
char isEmpty(){
if(top == -1){
return 'T';
}
return 'F';
}