2016-04-24 8 views
-2

グラフを表現する方法を学び、このコードを理解して理解しようとしているので、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; 
} 
+0

"この種の参照が可能なのはなぜか私の頭を奪うことはできません" - なぜそれは可能ではありませんか? – Siguza

+0

私はそれに慣れていない:Xとそれについてのオンラインメモを見つけることができないので、あなたは私を教えてくれませんか? – Hyune

+0

'[]'は配列インデックスであり、 '.'は構造体のメンバアクセスであり、' - > 'は逆参照と構造体メンバへのアクセスです(' a-> b'は '(* a).b'と同じです)。 ..そして彼らはちょうど連鎖しています。 [それらはすべて同じ優先順位を持つ](http://en.cppreference.com/w/c/language/operator_precedence)ので、ステートメントは '(((* graph).array)[i]と同義です。 head = NULL; 'が役立ちます。 – Siguza

答えて

0

この例は、わかりやすく理解するのに役立ちます。

typedef struct ITEM 
{ 
    int num; 
} ITEM; 

ITEM i; 
i.num = 123; // this is what you already know 

ITEM *p = &i; // p is pointer to i 
p->num = 456; // to change value of struct pointer member, use '->' 
// i.num is 456 now 

(*p).num = 789; // alternative way 
// i.num is 789 now 
+0

申し訳ありませんが、構造体を理解していますが、それは明らかにポインタのインデックス演算子を使用した部分でしたが、これまでに渡ったことはありません – Hyune

+0

@Hyune 'int * p'を10の整数として'malloc'それは '*(p + 9)= 123;と同じで、' p [9] = 123; 'を実行するために完全に有効です。 – raymai97