Search code examples
c++graphadjacency-matrix

Initializing an adjacency matrix in c++


I'm working on graph implementations in C++ and came across an implementation for an adjacency matrix that mostly made sense to me. The implementation uses an "init" function to initialize the matrix:

void init(int n) {

    numVertex = 0;
    numEdge = 0;

    mark = new int[n]; //initialize mark array
    for (int i = 0; i < numVertex; i++) {
        mark[i] = 0;
    }

    matrix = (int**) new int*[numVertex]; //make matrix
    for (int i = 0; i < numVertex; i++) {
        matrix[i] = new int[numVertex];
    }

    for (int i = 0; i < numVertex; i++) { //mark all matrix cells as false
        for (int j = 0; j < numVertex; j++) {
            matrix[i][j] = 0;
        }
    }
}

The line I'm confused about is:

 matrix = (int**) new int*[numVertex]; //make matrix

What does the (int**) aspect do? Why would I choose to use this instead of matrix = new int**[numVertex];?

Thanks so much!


Solution

  • (int**)value is a C-style cast operation.

    Notes:

    • Don't use those in C++, it tends to cause or hide problems, like mismatches between right and left side of an assignment.
    • The code is relatively low quality, proper C++ would rather use std::vector.
    • The code is also not complete, so little can be said with certainty about how it functions.