【发布时间】:2016-04-24 01:03:43
【问题描述】:
我正在尝试学习如何表示图形并遇到了这段代码,并试图理解它,因此我可以实现堆和 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;
}
【问题讨论】:
-
“我无法理解为什么这种引用是可能的”——为什么不可能?
-
因为我对它不熟悉:X,在网上找不到任何关于它的注释,你愿意赐教吗?
-
[]是数组索引,.是结构成员访问,->是取消引用加上结构成员访问(a->b将与(*a).b相同)...和他们只是被锁在一起。从they all have the same precedence 开始,如果有帮助,该语句将与(((*graph).array)[i]).head = NULL;同义。 -
这不是辅导网站。如果您在解码标准(而不是太复杂)标准 C 结构时遇到问题。您应该参考另一本书(教学法可能不适合您),或者您可能只是错过了关于
structs 和 pointers 的想法(显示的代码中没有数组)。 -
@Siguza:
[]是索引运算符。它应用于指针,而不是数组!