我试图建立一个程序,可以工作与邻接列表或矩阵图,为了做到这一点,老师教我们宣布毗邻为无效*,以便将其作为列表或矩阵进行投射。奇怪的输出的图形与空指针
正如你可以看到有很奇怪的事情B中节点挂出。
如果我尝试用代码块调试调试器会在if (L->target != target) {..
我认为有与initGraphList
动态分配的问题appendNodeList
一个Segmentation Fault
,但我不知道如何解决它。
您认为这里的问题是什么?这是分配吗?如果是,我该如何解决? 在此先感谢您的帮助!
代码:
的main.c
#include <stdio.h>
#include <stdlib.h>
#include "Graph.h"
int main(int argc, const char * argv[]) {
Graph G = NULL;
G = initGraphList(3);
addEdgeList(G, 0, 1, 1);
addEdgeList(G, 0, 2, 2);
addEdgeList(G, 1, 0, 3);
addEdgeList(G, 1, 2, 4);
addEdgeList(G, 2, 0, 5);
addEdgeList(G, 2, 1, 6);
printGraphList(G);
return 0;
}
Graph.h
#include "List.h"
struct TGraph {
void **adj;
int nodes_count;
};
typedef struct TGraph *Graph;
typedef struct AdjList{
List *nodes;
}AdjList;
Graph initGraphList(int);
void printGraphList(Graph G);
void addEdgeList(Graph G, int source, int target, float peso);
Graph.c
#include <stdio.h>
#include <stdlib.h>
#include "Graph.h"
Graph initGraphList(int nodes_count){
Graph G = (Graph)malloc(sizeof(struct TGraph));
G->adj = malloc(sizeof(AdjList));
G->nodes_count = nodes_count;
((AdjList *)(G->adj))->nodes = malloc(nodes_count * sizeof(List));
return G;
}
void printGraphList(Graph G) {
if (G != NULL) {
int i;
for(i = 0; i < G->nodes_count; i++) {
printf("%c -> ", i + 'A'); //I use this in order to print out the nodes as A,B,C,.. instead of 0,1,2,...
printList(((AdjList *)(G->adj))->nodes[i]);
puts("\n");
}
}
}
void addEdgeList(Graph G, int source, int target, float peso){
if(G != NULL){
if(source != target){
if(source < G->nodes_count){
if(target < G->nodes_count)
((AdjList*)(G->adj))->nodes[source]= appendNodeList(((AdjList*)(G->adj))->nodes[source], target, peso);
else
fprintf(stderr, "Il nodo %d non e' compreso nel grafo\n", target);
}else
fprintf(stderr, "Il nodo %d non e' compreso nel grafo\n", source);
}else
fprintf(stderr, "Non e' possibile inserire un arco che punta allo stesso nodo\n");
}else
fprintf(stderr, "Grafo invalido\n");
}
List.h
struct TList {
char target;
float peso;
struct TList* next;
};
List initNodeList(int info, float peso);
List appendNodeList(List L, int target, float peso);
void printList(List L);
List.c
#include <stdio.h>
#include <stdlib.h>
#include "List.h"
List initNodeList(int info, float peso) {
List L = malloc(sizeof(struct TList));
L->target = info;
L->peso = peso;
L->next = NULL;
return L;
}
List appendNodeList(List L, int target, float peso) {
if (L != NULL) {
if (L->target != target) {
L->next = appendNodeList(L->next, target, peso);
}
} else {
L = initNodeList(target, peso);
}
return L;
}
void printList(List L) {
if (L != NULL) {
printf(" %c(%f), ", L->target + 'A', L->peso);
printList(L->next);
}
}
你的头脑创造一个[___MCVE___](http://stackoverflow.com /帮助/ MCVE)? –
除了:;' –
@SouravGhosh 声明指针型的情况下,如果它的类型名和类型的随后的变量使用样式匈牙利记号来提示关闭读取器,如'typedef结构TGraph * pGraph使代码更易读它现在应该是一个MCVE,我删除了免费函数并添加了头文件来包含并将Graph.h与AdjList.h合并。 @WeatherVane我认为我是用'typedef结构TGraph *图形;'也许我不明白你的意思。 – Aster