I am learning C language - and currently studying the data-structures. I am implementing a basic Stack with an array, in a header file and I would like to be able to include this with different main programs.

My stack.h file:

#define STACK_SIZE 10 
typedef int elem; // Data Type of the stack array

// Stack Struct
struct stack {
  elem array[STACK_SIZE]; // Stack Data table
  int top; // Stack Head

typedef struct stack STACK;

I use typedef for the data-type of the stack array, within my stack.h.

However, I would like to be able to define a different data-type as per occasion from within any of my main.c files that would include my stack.h.

Something like below:

// Main.c
#include <stdio.h>
#include <stdlib.h>
#include "stack.h"

int main(){

    STACK st;
    // Here define somehow the desired data-type of my STACK.


Not sure if that does make sense and if it would be possible to do it that way... but if yes, how should I approach this?

1 Answers

Some programmer dude On Best Solutions

You mean like you want one stack of int, another stack of double, and a third stack of some custom structure? Then there's really no good built-in support for that in C.

It can be solved with dynamic allocation of an array of bytes, using a "create" or "initialize" function that is passed the size of the data. Then you use the element-size to figure out the position of each element in the byte-array.