Reputation: 1
#include <stdio.h>
#include <stdlib.h>
//**ptp just means it's a pointer point to a pointer...
void Push(int *top, int element,int **ptp){
*top = element;
//since *top is our pointer we use it to take whatever is in the element and store on the top.
//top is a location in memory not a number lol, first empty space
(*ptp) ++;
//this will add to our ptp(since it will incriment and move us to the next value rather than adding to the value.) when I call push
//ptp will never move but it will change the values
}
Top(int* top, int** ptp) {
//use the pointer to point to the first number in the stack
return *--top;
// the star says give me the value at the point before top
}
Pop(int*top, int**ptp){
if (*top == *ptp) {
printf("There is no top");
// do something to report stack underflow
}
else {
return (*ptp--);
return *-top;
}
#include <stdio.h>
main()
{
int Stack[4];
//creates an array with 4 element
int* top = Stack;
//pointer to the start of that memory
//step one create a push to add elements to our stack
Push(top, 12, &top);
//push is adding things
Push(top, 34, &top);
Push(top, 888, &top);
Push(top, 999, &top);
Pop(top,&top);
printf("This is the top: %d \n", Top(top, &top));
for (int i = 0; Stack[i] != Top(top, &top); i++) {
printf("%d , ", Stack[i]);
//This will print our list
}
}
Also coded an attempt at the pop
function I made and was able to pop the top of my stack however the top wouldn't update to read the new top of the stack. So I have [12,34,888,999]
and then I run my now deleted pop
function it would have returned [12,34,888]
but the top is still 999
. It's weird because I deleted my pop
function but when I run my code it still is in effect.
Upvotes: 0
Views: 61
Reputation: 52538
For a stack, you need the actual storage area, a pointer to the complete storage area, and a pointer or an index that tells you where the last pushed element is.
It’s best not to use individual variables but a struct containing all the things you need.
Upvotes: 1