当init_graph然后执行5 add_vertex然后has_vertex时,我收到了分段错误。
P表示它使用指针
#define SIZE (graph.size)
#define PSIZE (graph->size)
#define NODE (graph.node)
#define PNODE (graph->node)
#define NAME (graph.node[i].name)
#define PNAME (((graph->node)+i)->name)
#define NUM_DEST (graph.node[i].num_dest)
#define PNUM_DEST (((graph->node)+i)->num_dest)
#define DESTCOST (graph.node[i].destcost[j])
#define PDESTCOST (((graph->node)+i)->destcost)
#define DEST_NAME (graph.node[i].destcost[j].dest_name)
#define PDEST_NAME (((((graph->node)+i)->destcost)+j)->dest_name)
#define COST (graph.node[i].destcost[j].cost)
#define PCOST (((((graph->node)+i)->destcost)+j)->cost)
检查图形是否指向非NULL图并使大小计数器为0
void init_graph(Graph *graph) {
if (graph != NULL)
PSIZE = 0;
}
将new_vertex添加到节点列表(如果它不存在)
int add_vertex(Graph *graph, const char new_vertex[]) {
我获得当前尺寸,而尺寸增加1
int i = PSIZE++;
如果存在new_vertex则返回0
if (has_vertex(*graph, new_vertex))
return 0;
如果size不是1为另一个节点重新分配空间
否则为节点的大小分配内存
然后添加new_vertex并返回1
if (PSIZE > 1)
PNODE = realloc(PNODE, PSIZE * sizeof(node));
else PNODE = malloc(sizeof(node));
PNAME = malloc((strlen(new_vertex)+1) * sizeof(char));
strncpy(PNAME, new_vertex, strlen(new_vertex)+1);
return 1;
}
检查顶点是否存在
int has_vertex(Graph graph, const char name[]) {
int i;
检查传入的名称是否为非NULL
if (name != NULL)
遍历节点列表
for (i = 0; i < SIZE; i++)
检查:当前节点是否为名称
如果是这样:返回1
if (strcmp(NAME, name) == 0)
return 1;
return 0;
}
答案 0 :(得分:1)
很难理解你的代码,并且因为代码不完整而无法对其进行测试,但我可以怀疑的是:
//[1]
//i gets current size while size increases by 1
int i = PSIZE++;
//[2]
//if new_vertex exists return 0
if (has_vertex(*graph, new_vertex))
return 0;
我认为订单不正确,无论new_vertex是否存在,你都在递增PSIZE