c - 邻接矩阵没有正确分配
问题描述
我有一个v
表示节点数的图结构,**adjmatrix
它是邻接矩阵,我在用 0 初始化所有元素时遇到问题,我在adjmatrix[0][0]=0
.
结构如下所示:
struct Graph {
int V;
int **adjmatrix;
};
这是初始化图形的函数:
struct Graph *createGraph(int V) {
struct Graph *graph = (struct Graph *)malloc(sizeof(struct Graph));
graph->V = V;
graph->adjmatrix = (int *)malloc(V * V * sizeof(int));
int i, j;
for (i = 0; i < V; ++i) {
for (j = 0; j < V; j++) {
graph->adjmatrix[i][j] = 0; //here is where i get segmentation fault
}
}
return graph;
}
解决方案
graph->adjmatrix = (int **)malloc(V * sizeof(int*));
graph->adjmatrix = (int *)malloc(V * V * sizeof(int));
是不正确的。
你需要做的是:
graph->adjmatrix=malloc(V*sizeof(int *));
for (int i=0;i<V;i++){
graph->adjmatrix[i]=malloc(V*sizeof(int));
}
推荐阅读
- javascript - Var 返回“未定义”的 ASP.net mvc
- r - 如何更改 ggpubr/ggplot2 中的 p 值标签
- azure - Powershell : Get-AzureADGroupMember 获取嵌套组的所有成员
- android - 关于打开一个新活动以响应对片段内的 RecyclerView 项目的点击
- c++ - 构造链表时的无限循环
- logging - 事件查看器未记录 PC 关机
- amazon-web-services - 有多个 SQS 触发器时 Aws Lambda 中的优先级
- infinispan - Infinispan 是否支持 ANSI SQL?
- c# - Nhibernate queryover(或 lambda Linq)在投影中添加子查询计数
- mysql - 从数据块收到的 Sql 服务器连接丢失错误。连接池有用吗?