[英]What's wrong with this initialization? Why can't I succeed when I try to initialize a graph using the initialization function
using VS,C language.使用 VS,C 语言。 I try to initialization a Graph structure by a initialize fuction我尝试通过初始化函数初始化图形结构
#include<stdio.h> #define maxint 1000 #define mvnum 100 typedef struct { int vexs[mvnum]; int edges[mvnum][mvnum]; int n, e; }MGraph; void creatUDN(MGraph *G) { G = (MGraph*)malloc(sizeof(MGraph)); int i, j, k, w; scanf_s("%d", &(G->n)); scanf_s("%d", &(G->e)); for (i = 0; i < G->n; i++) scanf_s("%d", &(G->vexs[i])); for (i = 0; i < G->n; ++i) for (j = 0; j < G->n; ++j) G->edges[i][j] = maxint; for (k = 0; k < G->e; k++) { scanf_s("%d %d %d", &i, &j, &w); G->edges[i-1][j-1] = w; } for (i = 0; i < G->n; ++i) { for (j = 0; j <G->n; ++j) printf("%d\t", G->edges[i][j]); printf("\n"); } }
this is main function这是主要的 function
int main()
{
MGraph *g;
g=(MGraph*)malloc(sizeof(MGraph));
creatUDN(g);
**printf("%d", g->e);**
}
It shows that g still a Nullpointer after initialize.它表明 g 在初始化后仍然是一个 Nullpointer。 why?为什么?
Remove the assignment to G
in creatUDN
.在creatUDN
中删除对G
的分配。
G = (MGraph*)malloc(sizeof(MGraph));
Now your code will work.现在你的代码可以工作了。
You correctly allocated this data structure in main
and passed the pointer to creatUDN
, but then for some reason you allocated it again in creatUDN
so the data structure you allocated in main
remains unchanged.您在main
中正确分配了此数据结构并将指针传递给creatUDN
,但出于某种原因您在creatUDN
中再次分配了它,因此您在main
中分配的数据结构保持不变。
The other way you can do this is to return the allocated data structure from creatUDN
.另一种方法是从creatUDN
返回分配的数据结构。 That would look like this看起来像这样
MGraph *creatUDN() {
G = (MGraph*)malloc(sizeof(MGraph));
...
return G;
}
int main()
{
MGraph *g = creatUDN();
printf("%d", g->e);
}
You seem to have written something that's half way between these two methods.您似乎写了介于这两种方法之间的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.