嗨,我有這些結構代碼,
我需要使我的head[]陣列大小靈活
,例如,如果我的頭陣列大小為 9,我如何將其擴展為 10?!
struct Graph
{
// An array of pointers to Node to represent an adjacency list
struct Node *head[N];
};
// Data structure to store adjacency list nodes of the graph
struct Node
{
int dest, weight;
struct Node *next;
};
如何創建具有靈活頭部陣列大小的結構圖?
uj5u.com熱心網友回復:
struct具有靈活陣列成員的A通常有一個成員跟蹤陣列的大小,所以我假設它看起來像這樣:
struct Graph {
size_t nodes;
struct Node *head[];
};
要為此類分配記憶體,struct您需要呼叫malloc并總結sizeof(Graph)(其中靈活成員的范圍被計為0)和sizeof(struct Node*[the_number_of_node_pointers_you_want]).
例子:
struct Graph *Graph_create(size_t nodes) {
struct Graph *g = malloc(sizeof *g sizeof(struct Node*[nodes]));
if(g) g->nodes = nodes;
return g;
}
如果您以后想擴展靈活陣列,您可以realloc以類似的方式使用:
// this returns true or false depending on if expansion succeeded
bool Graph_expand(struct Graph **g, size_t nodes) {
if(*g && (*g)->nodes < nodes) {
struct Graph *ng = realloc(*g, sizeof *ng sizeof(struct Node*[nodes]));
if(ng) {
*g = ng;
(*g)->nodes = nodes;
return true;
}
}
return false;
}
演示
在擴展陣列時要注意一點:realloc如果不能就地擴展分配,則可能會移動記憶體。如果出現這種情況,你有任何指標,以你的舊Graph物件,他們將一直是無效的realloc。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/399827.html
上一篇:VScode除錯器輸出未顯示
