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;
};
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;
}
// Adds an edge to an undirected graph
void addEdge(struct Graph* graph, int src, int dest)
{
// Add an edge from src to dest. A new node is added to the adjacency
// list of src. The node is added at the begining
struct AdjListNode* newNode = newAdjListNode(dest);
newNode->next = graph->array[src].head;
graph->array[src].head = newNode;
// Since graph is undirected, add an edge from dest to src also
newNode = newAdjListNode(src);
newNode->next = grap`enter code here`h->array[dest].head;
graph->array[dest].head = newNode;
}
特别是
graph->array[i].head = NULL;
因为Graph中的数组成员是指向AdjList的指针,所以为什么是
graph->array[i]->head = NULL;
没用过?
我知道当我们访问不是指针的struct成员时会使用.
运算符。
somestructpointer -> itsmember
基本上是糖衣
(*somestructpointer).itsmember
我不明白发生了什么。 HELP。
答案 0 :(得分:4)
AdjList* array
是指向数组数组的指针。基本上,写array[i]
等同于写*(array + i)
。
所以我们有:
graph->array[i].head
变为
(*(graph->array + i)).head
作为一个有趣的奖金并且让你更加困惑,你也可以写i[array]
,因为它基本上也是*(i + array)
。
答案 1 :(得分:2)
graph
是一个指针
graph->array
取消引用上面的指针以获取数组变量
graph->array[i]
使用数组表示法来访问位置i
的成员。
我们到达的成员是struct AdjList
类型,它不是指针。这是一个struct
。所以点(.
)是合适的。