【问题标题】:Using structs and arrays使用结构和数组
【发布时间】: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,在网上找不到任何关于它的注释,你愿意赐教吗?
  • [] 是数组索引,. 是结构成员访问,-&gt; 是取消引用加上结构成员访问(a-&gt;b 将与 (*a).b 相同)...和他们只是被锁在一起。从they all have the same precedence 开始,如果有帮助,该语句将与(((*graph).array)[i]).head = NULL; 同义。
  • 这不是辅导网站。如果您在解码标准(而不是太复杂)标准 C 结构时遇到问题。您应该参考另一本书(教学法可能不适合您),或者您可能只是错过了关于 structs 和 pointers 的想法(显示的代码中没有数组)。
  • @Siguza: [] 是索引运算符。它应用于指针,而不是数组!

标签: c arrays struct


【解决方案1】:

这个例子应该可以帮助你轻松理解。

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

【讨论】:

  • 对不起,我理解结构,它只是使用 [] 的部分,显然它是指针的索引运算符,以前从未遇到过
  • @Hyune 如果你有mallocint *p 10 个整数,那么p[9] = 123; 是完全有效的,因为它与*(p + 9) = 123; 相同。
猜你喜欢
  • 1970-01-01
  • 2010-10-27
  • 2018-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-21
  • 1970-01-01
相关资源
最近更新 更多