The problem here is to design an API for the call stack in C. The items to be pushed onto the stack can be of different sizes, ranging from 1 byte to N bytes (and can be a mixture of them- for example, push a char first, then push an int, then push a struct). The stack can be a implemented as a linked list or dynamic array, there are no constraints.
My solution:
Since the datatype of the item that will be pushed onto the stack is unknown, I figured that using a void* pointer might be a suitable solution.
Question:
Is this the best way of implementing it, from an engineering perspective? Is there a better approach? Please find my code below. Thanks!
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct stack_node snode;
struct stack_node{
snode *next;
void *data;
};
bool push(snode **top, void* data)
{
snode *current = (snode*)malloc(sizeof(snode));
if(!current)
return false;
current->data = data;
current->next = *top;
*top = current;
return true;
}
bool pop(snode **top, void **data)
{
snode* current;
current = *top;
if(!current)
return false;
*data = current->data;
*top = current->next;
free(current);
return true;
}
int main()
{
int num=0, i;
snode* top = NULL;
int arr[10] = {1,2,3,4,5,6,7,8,9,10};
for(i = 0; i < 10 ; i++ )
{
if(!push(&top, &arr[i]))
printf("error allocating memory\n");
}
void *data;
while(pop(&top, &data))
{
printf("popped %d\n", *((int*)data));
}
return 0;
}
Using a pointer would be a good option if the data wasn’t suppose to exist on the stack. What if I want to pass more than 4 bytes of data from stack? pointer would not be the best option there. In my opinion you should insert data byte by byte onto the stack. Which means
unsigned charwould be a good option as well.