使用结构和数组

时间:2016-04-24 01:03:43

标签: c arrays struct

我正在尝试学习如何表示图形并遇到此代码并尝试理解它,因此我可以使用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;
}

1 个答案:

答案 0 :(得分: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