Well guys, I'm doing graph theory in C, and I've tried using dynamic allocation to create an array. Also, my code has a function to populate the array with 1 in the received indexes. However I have some error in the array allocation or in its padding.
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);
}