Search code examples
cgraph-algorithmadjacency-matrix

Graph with adjacency matrix in C


I have this struct:

struct graph {
    int** adj; /**< Adjacency matrix. */
    int n; /**< Number of nodes in graph. */
};

and I have to create a void graph into this function:

struct graph *graph_create(int nodes) {
  //To implement
}

How can I create a matrix using that double pointer int** adj?


Solution

  • Here is the way to define a matrix with malloc() that i catch from GeeksForGeeks with some edition.

    2D integer Matrix with int ** and malloc()

    int r = 3, c = 4, i, j, count;
    
    //arr[r][c]
    int **arr = (int **)malloc(r * sizeof(int *));
    
    for (i=0; i<r; i++){
        *(arr +i) = (int *)malloc(c * sizeof(int));
        //arr[i] = (int *)malloc(c * sizeof(int));
    }
    
    // Note that arr[i][j] is same as *(*(arr+i)+j)
    count = 0;
    for (i = 0; i <  r; i++)//3
        for (j = 0; j < c; j++)//4
            arr[i][j] = ++count;  // OR *(*(arr+i)+j) = ++count
    
    for (i = 0; i <  r; i++){
        printf("\n");
        for (j = 0; j < c; j++){
            printf("%d ", arr[i][j]);
        }
    }
    

    And we can put these code inside graph_create(int nodes) function.

    Code

    struct graph {
        int** adj; /**< Adjacency matrix. */
        int n; /**< Number of nodes in graph. */
    }G;
    
    
    struct graph *graph_create(int nodes) {
    
        struct graph * tmp = &G;
        int r = nodes, c = nodes, i, j, count;
    
        //arr[r][c]
        G.adj = (int **)malloc(r * sizeof(int *));
    
        for (i=0; i<r; i++){
             *(G.adj + i) = (int *)malloc(c * sizeof(int));
             //arr[i] = (int *)malloc(c * sizeof(int));
        }
    
    
        count = 0;
        for (i = 0; i <  r; i++)//3
          for (j = 0; j < c; j++)//4
             G.adj[i][j] = ++count;  // OR *(*(arr+i)+j) = ++count
    
        for (i = 0; i <  r; i++){
            printf("\n");
            for (j = 0; j < c; j++){
                printf("%d ", G.adj[i][j]);
            }
        }
    
        return tmp;
    
    }
    
    
    
    int main()
    {
    
    
        struct graph * d = graph_create(5);
    
        printf("\n");
        return 0;
    }
    

    We know the adjacency Matrix of a graph have n*n dimension. for that we use nodes as row and column.

    Edit

    For secure working with malloc() function we must free the memory locations that is reserved by malloc(), by calling free() with these blocks. (similar to Mobius answer)

    just before return 0; statement in main() call this:

    free ((*d).adj);

    Required header files:

    #include <stdio.h>
    #include <stdlib.h> // for** malloc()**, **free()**