我问了一个关于结构内动态指针的分配和重新分配的问题。但现在我在一个结构中有一个双指针组件。
我想在添加顶点后重新分配图的邻接矩阵。
双指针的重新分配有效,但是当我想在循环中重新分配指针(双指针指向的指针)时,程序在第一个循环运行时停止并出现分段错误......
这是我的想法(画在油漆中......) myIdea
为了更好的可读性,我划分了我的代码
这是代码第 1 部分:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
struct Vertices
{
int id;
char name[15];
float xPos;
float yPos;
};
struct Edge
{
int id;
struct Vertices *start;
struct Vertices *end;
};
struct Graph
{
int VertexCounter;
struct Vertices *vertex;
struct Edge **adjMat;
};
第 2 部分与 updateAdjMat () 中的重新分配问题:
//Initializing graph
void initGraph(struct Graph **graph)
{
*graph = calloc (1, sizeof(struct Graph **));
if (!*graph) {
perror ("calloc-*graph");
exit (EXIT_FAILURE);
}
(*graph)->vertex = NULL;
(*graph)->adjMat = NULL;
/*
(*graph)->adjMat = calloc (1, sizeof (struct Edge **));
if (!(*graph)->adjMat) {
perror ("calloc-(*graph)->adjMat");
exit (EXIT_FAILURE);
}
*/
(*graph)->VertexCounter = 0;
}
void updateAdjMat (struct Graph *graph)
{
int i;
void *tmp = realloc (graph->adjMat, graph->VertexCounter * sizeof (struct Edge *));
if (!tmp)
{
perror ("realloc-graph->adjMat");
exit (EXIT_FAILURE);
}
graph->adjMat = tmp;
for (i = 0; i < graph->VertexCounter; i++)
{
void *tmp = realloc (*(graph->adjMat + i), (graph->VertexCounter) * sizeof (struct Edge));
if(!tmp)
{
perror ("realloc-*(graph->adjMat + i)");
exit (EXIT_FAILURE);
}
*(graph->adjMat + i) = tmp;
}
}
第 3 部分与工作代码:
//reallocating the memory for the vertex pointer
void addVertex (struct Graph *graph, char name[15], float x, float y)
{
void *tmp = realloc (graph->vertex, (graph->VertexCounter + 1) * sizeof(*graph->vertex));
if (!tmp) {
perror ("realloc-(*graph)->vertex");
exit (EXIT_FAILURE);
}
graph->vertex = tmp;
(graph->vertex + graph->VertexCounter)->id = graph->VertexCounter + 1;
strcpy((graph->vertex + graph->VertexCounter)->name, name);
(graph->vertex + graph->VertexCounter)->xPos = x;
(graph->vertex + graph->VertexCounter)->yPos = y;
graph->VertexCounter++;
updateAdjMat(graph);
}
void menu_addVertex (struct Graph *graph)
{
char name[15];
float xPos, yPos;
printf ("\nWhats the name of the vertex?\n");
scanf ("%s", &name);
printf ("\nX Coordinate?\n");
scanf ("%f", &xPos);
printf ("\nY Coordinate?\n");
scanf ("%f", &yPos);
printf ("\n");
addVertex (graph, name, xPos, yPos);
}
//free the allocated memory
void freeGraph (struct Graph *graph)
{
free (*(graph->adjMat));
free (graph->adjMat);
free (graph->vertex);
free (graph);
}
在我的 Main 中,我只有一个菜单,通过调用 addVertex 添加具有名称和 x、y 坐标的新顶点