Graphs - return a pointer to the adjacency matrix

Asked

Viewed 135 times

1

I am implementing a work of Graph Theory that deals with the game Flood-It which is a problem in flooding in Graphs.

I’m right at the beginning and implemented the graph structure yet. The structure of it is:

typedef struct {
    int V; 
    int A; 
    int **adj; 
} Grafo;

The third field must be a pointer to the adjacency matrix of the graph. The function that creates the matrix is the following:

static int ** MATRIZADJint(int linhas,const int colunas, int valor){
    int **m = malloc(linhas * sizeof(int *)); // aloca linhas
    for (vertice i = 0; i < colunas; ++i)
        m[i] = malloc(colunas * sizeof(int)); // aloca colunas
    for (vertice i = 0; i < linhas; ++i)
        for (vertice j = 0; j < colunas; ++j)
            m[i][j] = valor; // preenche a matriz de adjacencias inicialmente com 0's
    return m;
}

Unfortunately Visual Studio is not accepting the implementation, presenting the following error message:

malloc - a value of type "void *" cannot be used to initialize an entity of type "int **" = - a value of type "void *" cannot be used to initialize an entity of type "int **"

Does anyone know what it can be?

  • 1

    Related: https://answall.com/q/95784/132

1 answer

2


Just cast a cast for the right type on malloc:

static int ** MATRIZADJint(int linhas, const int colunas, int valor) {
    int **m = (int **) malloc(linhas * sizeof(int *)); // aloca linhas
    for (int i = 0; i < colunas; ++i) {
        m[i] = (int *) malloc(colunas * sizeof(int)); // aloca colunas
    }
    for (int i = 0; i < linhas; ++i) {
        for (int j = 0; j < colunas; ++j) {
            m[i][j] = valor; // preenche a matriz de adjacencias inicialmente com 0's
        }
    }
    return m;
}

This is because there are a few cases where C++ is not compatible with C and this is one of them. The function malloc has a kind of return void *. The C accepts that a void * is assigned to any pointer without problems, but C++ requires the cast.

I also don’t understand why you declared the variables of the ties for with vertice instead of int.

In addition, I strongly recommend the use of { and } in the bonds for to avoid certain kinds of problems and unpleasant surprises. But that would already be subject to another question.

  • Thank you very much. In the header has a #define Vertice int, so! Thank you for the advice for the ties too! Thank you very much indeed

  • @Thiagoroberto If this answer solved your problem and there is no doubt left, mark it as correct/accepted by clicking on " " that is next to it, which also marks your question as solved. If you still have any questions or would like further clarification, feel free to comment.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.