Graphs - return a pointer to the adjacency array

1

I'm implementing a Graph Theory work that deals with the Flood-It game which is a flood problem in Graphs.

I'm fine at the beginning and implemented the graph structure yet. Its structure 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 array is as follows:

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, with the following error message:

  

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

Does anyone know what it can be?

    
asked by anonymous 18.05.2018 / 22:49

1 answer

2

Just make a cast for the correct type in 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 happens because there are a few cases where C ++ is not compatible with C and this is one of them. The malloc function has a return type void * . C accepts that void * is assigned to any pointer without problems, but C ++ requires cast.

I also did not understand why you declared the variables of the for loops with vertice instead of int .

In addition, I highly recommend using { and } in for loops to avoid certain types of problems and unpleasant surprises. But that would be a subject for another question.

    
18.05.2018 / 23:06