2
Well, guys, I’m doing graph theory on C, and I tried to use dynamic allocation to create an array. Also, my code has a function to fill the matrix with 1 in the received indexes. But I have some error in the allocation of the matrix or in its filling.
The code hangs and returns 3221225477
#include<stdlib.h>
#include<stdio.h>
struct digraph //Estrutura do grafo, V e A são contadores, matrix_adj é um ponteiro para um array de ponteiros
{
int V , A;
int **matrix_adj;
};
typedef struct digraph* Digraph;
int **matrix_alloc(int r,int c,int val);
Digraph graph_alloc(int vertex);
void insert(Digraph G, int v, int w);
void show(Digraph G);
int main(void)
{
Digraph G;
G = graph_alloc(6);
insert(G, 1,2);
insert(G, 1,3);
insert(G, 2,4);
insert(G, 3,4);
insert(G, 4,5);
insert(G, 5,6);
show(G);
return 0;
}
int **matrix_alloc(int r,int c,int val)
{
int i, j;
int **matrix = (int**)malloc(r*sizeof(int*));// aloca linhas
for(i=0;i<r;i++)
{
matrix[i] = (int*)malloc(c*sizeof(int));//aloca colunas
for(j=0;j<c;j++)
{
matrix[i][j] = val;
}
}
return matrix;
}
Digraph graph_alloc(int vertex)
{
Digraph G;
G->V = vertex;
G->A = 0;
G->matrix_adj = matrix_alloc(vertex, vertex, 0);
return G;
}
void insert(Digraph G,int v, int w)
{
if(G->matrix_adj[v][w] == 0)
{
G->matrix_adj[v][w] = 1;
G->matrix_adj[w][v] = 1;
G->A++;
}
}
void show(Digraph G)
{
int v, w;
for(v=0; v<G->V; v++)
{
for(w=0; w<G->V;w++)
{
printf("%d ", G->matrix_adj[v][w]);
}
printf("\n");
}
printf("\n");
printf("Vertices: ", G->V);
printf("Arestas: ", G->A);
}
What is the mistake? Where?
– Maniero
The program opens and already stops working, but this large number of returns that I mentioned makes me believe that it is some memory error, in the function Insert or matrix_alloc
– Gabriel Yassunaga
Show the table or program before that? I tried the code and it looks good
– Fábio Morais
In the computer that I am currently, it stops working before showing, in q I have at home, shows the output matrix, but stands still for a few seconds and then the main function returns 3221225477
– Gabriel Yassunaga
Strange, I’m not having mistakes, the program goes well
– Fábio Morais