gpt4 book ai didi

c - 使用结构体和数组

转载 作者:行者123 更新时间:2023-11-30 20:36:05 26 4
gpt4 key购买 nike

我正在尝试学习如何表示图形,并遇到了这段代码,并尝试理解它,以便我可以实现堆和 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;
}

最佳答案

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

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

关于c - 使用结构体和数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36818173/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com