I am writing a code for implementing Adjacency Matrix for graph.But I am getting runtime error.Can anyone suggest where I am wrong?
Code:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
struct Graph{
int V;
int E;
int **Adj;
};
void test(struct Graph *graph)
{
graph->E = 5;
graph->V = 4;
graph->Adj = malloc(sizeof(graph->V * graph->V));
graph->Adj[0][0] = 9;
graph->Adj[0][1] = 7;
graph->Adj[0][2] = 2;
graph->Adj[0][3] = 5;
printf("Hello %d\n",graph->Adj[0][2]);
}
int main()
{
struct Graph *graph = malloc(sizeof(struct Graph));
test(graph);
}
If I do the same in main function it works.I don't understand what am I doing wrong when I write test function and do it?
Code when done in main function:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
struct Graph{
int V;
int E;
int **Adj;
};
int main()
{
struct Graph *graph = malloc(sizeof(struct Graph));
graph->E = 5;
graph->V = 4;
graph->Adj = malloc(sizeof(graph->V * graph->V));
graph->Adj[0][0] = 9;
graph->Adj[0][1] = 7;
graph->Adj[0][2] = 2;
graph->Adj[0][3] = 5;
printf("Hello %d\n",graph->Adj[0][2]);
}
Getting Runtime error.While debugging for test function
it works till graph->Adj = malloc(sizeof(graph->V * graph->V));
but at graph->Adj[0][0] = 9;
it gives error.Why???
You are doing a wrong malloc. You are using pointer to pointer. So, you will have to malloc first to get the array pointer allocated dynamically. Then you will have to allocate it for every row.
Try this:
graph->Adj = (int **)malloc(graph->v * sizeof(int *));
for (i=0; i<graph->v; i++)
graph->Adj[i] = (int *)malloc(graph->v * sizeof(int));