結構定義
struct Link_Info {
int Destination_VertexID;
int Vertex_To_Vertex_LinkID;
int Cost_of_Link;
};
struct Vertex_Info {
int OutDegree;
int Vertex_Num;
Link_Info* out = new Link_Info[8]; // 內層動態數組
};
Vertex_Info* Vertex_Chain = new Vertex_Info[600]; // 外層動態數組
正確釋放順序
void FreeVertexChain(Vertex_Info* chain, int count) {
if (!chain) return;
for (int i = 0; i < count; ++i) {
delete[] chain[i].out; // 1. 先釋放每個元素的內層數組
chain[i].out = nullptr;
}
delete[] chain; // 2. 再釋放外層數組
chain = nullptr;
}
// 調用
FreeVertexChain(Vertex_Chain, 600);
關鍵原則
- 分配幾層,釋放幾層,順序相反:先內後外。
- 釋放後置空指針,防止二次釋放。
- 若構造函數分配內存,析構函數中釋放(RAII),推薦使用
std::vector/std::unique_ptr 自動管理。
現代 C++ 改寫(推薦)
struct Vertex_Info {
int OutDegree;
int Vertex_Num;
std::vector out; // 自動管理內存
};
std::vector Vertex_Chain(600); // 無需手動釋放