【发布时间】:2018-11-11 03:15:16
【问题描述】:
我正在实现一个基于 C 中的邻接矩阵的图形程序。 但是我在初始化矩阵(分配零值)时遇到了分段错误。 我不确定我在访问双指针时是否犯了任何错误。
谁能帮我解决这个问题?
代码如下:
struct Graph {
int V;
int E;
int **adj;
};
struct Graph *addelements() {
int i,j,a,u,v;
struct Graph *G= (struct Graph*)malloc(sizeof(struct Graph*));
printf("Enter the number of vertices and edges : ");
scanf("%d %d", &G->V,&G->E);;
printf("%d, %d\n",G->V ,G->E);
//G->adj = (int **)malloc(sizeof(int **)*(G->V * G->E));
G->adj = malloc(sizeof(G->V * G->E));
//Initialization of vertices
for(i=0;i<=G->V;i++) {
for(j=0;i<=G->V;j++) {
G->adj[i][j]=0;
}
}
//Reading the edges;
for(i=0;i<G->E;i++) {
printf("Enter the source and destination : ");
scanf("%d %d\n", &u,&v);
G->adj[u][v]=1;
G->adj[v][u]=1;
}
//printing the matrix
for(i=0;i< G->V;i++) {
for(j=0;i< G->V;j++) {
printf("%d", G->adj[i][j]);4
}
}
return G;
}
int main() {
struct Graph *a= (struct Graph*)malloc(sizeof(struct Graph*));
a = addelements();
}
输出:
输入顶点数和边数:4 5
分段错误(核心转储)
【问题讨论】:
-
欢迎来到 Stack Overflow!请edit你的问题告诉我们你做了什么样的调试。我希望您已经在 Valgrind 或类似的检查器中运行了您的minimal reproducible example,并使用诸如 GDB 之类的调试器进行了调查。确保您也启用了全套编译器警告。这些工具告诉了你什么,它们缺少什么信息?并阅读 Eric Lippert 的 How to debug small programs。
-
顺便说一句,你知道
sizeof (G->V * G->E)和sizeof (int)是一样的吗?也许您想改为malloc(sizeof *G->adj * G->V * G->E);?
标签: c struct segmentation-fault malloc