I am curious as to what is happening to my pointers and everything once I call malloc to create space for 5 integers to try to make a stack.
Code:
#include <stdio.h>
#include <stdlib.h>
void add(int * TOP, int * stack);
int main()
{
int *stack = NULL;
int *TOP = NULL;
stack = (int *)malloc (5 * sizeof(int));
TOP = stack;
int b = 0;
int (*f[])(int * TOP ,int * stack) = {add};
while (b == 0){
printf("What would you like to do? Press 0 to stack.");
scanf("%d", &b);
printf("%d",f[b]( TOP, stack));
printf("Please enter another number.");
scanf("%d", &b);
}
return 0;
}
void add(int * TOP, int * stack)
{
int a = 0;
printf("Please enter a number to stack.");
scanf("%d", &a);
if (TOP == stack + 5)
printf("The stack is full.");
else{
*TOP = a;
printf("The number put on the stack was %d", *TOP);
TOP++;
}
}
I am guessing that when I initialize stack to malloc, stack now stores the starting address of where the space is taken out, and also assigns TOP that adress too. I get the choice from the user (b) to get the instruction to try to push on the stack. I was told that the if statement in the function checks if the stack has passed the bounds of 5 elements. If not, it assigns the scanned variable and puts it into what TOP is pointing to and increments TOP to the next address. It is not working and am wanting to see where my logic is wrong, because this is all very confusing to me. Thank you.