#include<stdio.h>
#include<string.h>
#include <stdlib.h>
# define MaxVNum 100
using namespace std;
// REF:
https://www.youtube.com/watch?v=xfL84Kn72nA
typedef struct e {
int from;
int to;
float weight;
} edge;
edge edges[256], *Edge;
int numberOfEdges = 0;
//Edge E;
//E = (Edge)malloc(sizeof(edge));
typedef struct v {
int v;
}vertex;
vertex vertexes[256];
int numberOfV = 0;
void readMap(){
FILE * map;
map = fopen("map.txt", "r");
while (!feof(map)) {
fscanf(map, "%d %d %f", &edges[numberOfEdges].from, &edges[numberOfEdges].to, &edges[numberOfEdges].weight);
numberOfEdges++;
}
fclose(map);
}
void printEdges() {
for (int i = 0; i < numberOfEdges; i++) {
printf("%d %d %f\n", edges[i].from, edges[i].to, edges[i].weight);
}
}
unsigned int exist(int s, vertex a[]) {
unsigned int exist = 0;
for (int i = 0; i < numberOfV; i++) {
if (s - a[i].v == 0) {
exist = 1;
}
}
return exist;
}
void readVertex() {
for (int i = 0; i < numberOfEdges; i++) {
if (!exist(edges[i].from, vertexes)) {
vertexes[numberOfV].v = edges[i].from;
numberOfV++;
}
if (!exist(edges[i].to, vertexes)) {
vertexes[numberOfV].v = edges[i].to;
numberOfV++;
}
}
}
void printVertex() {
printf("\n Our Vertex: ");
for (int i = 0; i < numberOfV; i++) {
printf("%d\t", vertexes[i].v);
}
}
typedef struct graph {
int Nv;
int Ne;
int matrix[MaxVNum][MaxVNum];
}graph,*MyGraph;
graph g;
//initialize teh graph that has numebr of V vertex
void InitGraph(MyGraph G) {
G->Nv = numberOfV;
G->Ne = 0;
//initialize the weight of each edge
for (int i = 0; i < numberOfV; i++) {
for (int j = 0; j < numberOfV; j++) {
G->matrix[i][j] = 0;
}
}
}
//insert the weight
void insertEdge(MyGraph G) {
for (int i = 0; i < numberOfEdges; i++) {
G->matrix[Edge->from][Edge->to] = Edge->weight;
G->matrix[Edge->to][Edge->from] = Edge->weight;
}
}
void printGraph() {
for (int j = 0; j < numberOfV; j++)
{
for (int i = 0; i < numberOfV; i++){
printf("%5d", g.matrix[i][j]);
printf("\n");
}
}
}
int main() {
readMap();
printEdges();
readVertex();
printVertex();
MyGraph G;
G = (MyGraph)malloc(sizeof(graph));
InitGraph(G);
insertEdge(G);
printGraph();
}
Terminal:Segmentation fault (core dumped)
I know there are some errors when constructing the matrix. How to fix it? Thanks for your kindly help.