我有两段代码:
gb_Graph = (int **)malloc(sizeof(int*)*gb_nVertices);
if (gb_Graph == NULL)
return false;
gb_Open = (VERTEX *)malloc(sizeof(VERTEX*)*gb_nVertices);
if (gb_Open == NULL)
return false;
gb_Close = (VERTEX *)malloc(sizeof(VERTEX*)*gb_nVertices);
if (gb_Close == NULL)
return false;
for (i = 0; i < gb_nVertices; i++)
{
gb_Graph[i] = (int*)malloc(sizeof(int)*gb_nVertices);
if (gb_Graph[i] == NULL)
return false;
for (j = 0; j<gb_nVertices; j++)
fscanf(gb_fInput, "%d", &(gb_Graph[i][j]));
}
for (i = 0 ; i<gb_nVertices; i++)
{
gb_Open[i].Exist = false;
gb_Open[i].ParentName = -1;
gb_Open[i].CostPath = 0;
fscanf(gb_fInput, "%d", &(gb_Open[i].CostHeuristic));
gb_Close[i].Exist = false;
gb_Close[i].ParentName = -1;
gb_Close[i].CostPath = 0;
gb_Close[i].CostHeuristic = gb_Open[i].CostHeuristic;
}
gb_Open[gb_nStart].Exist = true;
和
gb_Graph = (int **)malloc(sizeof(int*)*gb_nVertices);
if (gb_Graph == NULL)
return false;
for (i = 0; i < gb_nVertices; i++)
{
gb_Graph[i] = (int*)malloc(sizeof(int)*gb_nVertices);
if (gb_Graph[i] == NULL)
return false;
for (j = 0; j<gb_nVertices; j++)
fscanf(gb_fInput, "%d", &(gb_Graph[i][j]));
}
gb_Open = (VERTEX *)malloc(sizeof(VERTEX*)*gb_nVertices);
if (gb_Open == NULL)
return false;
gb_Close = (VERTEX *)malloc(sizeof(VERTEX*)*gb_nVertices);
if (gb_Close == NULL)
return false;
for (i = 0 ; i<gb_nVertices; i++)
{
gb_Open[i].Exist = false;
gb_Open[i].ParentName = -1;
gb_Open[i].CostPath = 0;
fscanf(gb_fInput, "%d", &(gb_Open[i].CostHeuristic));
gb_Close[i].Exist = false;
gb_Close[i].ParentName = -1;
gb_Close[i].CostPath = 0;
gb_Close[i].CostHeuristic = gb_Open[i].CostHeuristic;
}
gb_Open[gb_nStart].Exist = true;
在第一个代码中,它会导致错误。如果我在 2 个代码中从文件读取值到 gb_Graph 变量后放置一个断点,则没有区别。但在那之后,在 gb_Open[gb_nStart].Exist = true; ,在第一个代码中,gb_Graph 的值被修改。
我认为这是内存分配的顺序。正确的?
带变量:
VERTEX *gb_Open;
VERTEX *gb_Close;
int **gb_Graph;
请解释一下为什么会出错?我使用 VS C++ 2012