グラフを表現する方法を学び、このコードを理解して理解しようとしているので、dijkstrasアルゴリズムと共にヒープを実装できます。構造体と配列を使用する
私は、この構造体の参照に慣れていない午前:
graph->array[i].head = NULL;
は、構造体のために、この合法的ですか?私はCの本の中でこの種のものは見かけませんでした。それはコードが上記の行の配列に十分なメモリを割り当てたからですか?
graph->array = (struct AdjList*) malloc(V * sizeof(struct AdjList));
物事を文脈に入れるためのコードの一部。助けてください、本当にこの構造体の構文を理解しようとすると、この種の参照が可能なのを私の頭に浮かべることはできませんか?
// A C Program to demonstrate adjacency list representation of graphs
#include <stdio.h>
#include <stdlib.h>
// A structure to represent an adjacency list node
struct AdjListNode
{
int dest;
struct AdjListNode* next;
};
// A structure to represent an adjacency list
struct AdjList
{
struct AdjListNode *head; // pointer to head node of list
};
// A structure to represent a graph. A graph is an array of adjacency lists.
// Size of array will be V (number of vertices in graph)
struct Graph
{
int V;
struct AdjList* array;
};
// A utility function to create a new adjacency list node
struct AdjListNode* newAdjListNode(int dest)
{
struct AdjListNode* newNode =
(struct AdjListNode*) malloc(sizeof(struct AdjListNode));
newNode->dest = dest;
newNode->next = NULL;
return newNode;
}
// A utility function that creates a graph of V vertices
struct Graph* createGraph(int V)
{
struct Graph* graph = (struct Graph*) malloc(sizeof(struct Graph));
graph->V = V;
// Create an array of adjacency lists. Size of array will be V
graph->array = (struct AdjList*) malloc(V * sizeof(struct AdjList));
// Initialize each adjacency list as empty by making head as NULL
int i;
for (i = 0; i < V; ++i)
graph->array[i].head = NULL;
return graph;
}
"この種の参照が可能なのはなぜか私の頭を奪うことはできません" - なぜそれは可能ではありませんか? – Siguza
私はそれに慣れていない:Xとそれについてのオンラインメモを見つけることができないので、あなたは私を教えてくれませんか? – Hyune
'[]'は配列インデックスであり、 '.'は構造体のメンバアクセスであり、' - > 'は逆参照と構造体メンバへのアクセスです(' a-> b'は '(* a).b'と同じです)。 ..そして彼らはちょうど連鎖しています。 [それらはすべて同じ優先順位を持つ](http://en.cppreference.com/w/c/language/operator_precedence)ので、ステートメントは '(((* graph).array)[i]と同義です。 head = NULL; 'が役立ちます。 – Siguza