cmatrixgraph-theoryadjacency-matrixstatic-memory-allocation

Parameterizing type definition at compile time


What is a good way to define this graph data structure:

typedef struct
{
    unsigned short isExists : 1;
    WEIGHT_TYPE weight;
} Weight;

typedef struct
{
    Weight adjacencyMatrix[VERTICES_NUM][VERTICES_NUM];
    VERTEX_TYPE vertices[VERTICES_NUM];
} Graph;

using a value for VERTICES_NUM defined at compile time?

I am looking for a better solution than defining VERTICES_NUM before including the .h file that contains the above, and I do not want to use dynamic allocation.


Solution

  • I would first approach the problem with a macro that will define the types for you.

    #define DEFINE_GRAPH(NAME, WEIGHT_TYPE, VERTEX_TYPE, VERTICES_NUM) \
            DEFINE_WEIGHT_TYPE(NAME, WEIGHT_TYPE); \
            DEFINE_GRAPH_TYPE(NAME, VERTEX_TYPE, VERTICES_NUM)
    
    #define DEFINE_WEIGHT_TYPE(NAME, WEIGHT_TYPE) \
            typedef struct { \
                unsigned short isExists : 1; \
                WEIGHT_TYPE weight; \
            } WEIGHT(NAME)
    
    #define DEFINE_GRAPH_TYPE(NAME, VERTEX_TYPE, VERTICES_NUM) \
            typedef struct { \
                WEIGHT(NAME) adjacencyMatrix[VERTICES_NUM][VERTICES_NUM]; \
                VERTEX_TYPE vertices[VERTICES_NUM]; \
            } GRAPH(NAME)
    
    #define WEIGHT(NAME) NAME ## _Weight
    #define GRAPH(NAME) NAME ## _Graph
    

    Now, a user could do something like:

    DEFINE_GRAPH(Test, char, float, 10);
    

    And in their code, they would use the data structure like this:

    int main () {
        GRAPH(Test) g;
        /* ... */
    }