ABHINAV RANA - 9 months ago 68

C Question

`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;

}

Specifically

`graph->array[i].head = NULL;`

- Ok so the graph is a pointer of type Graph
- hence uses -> to access array which is an object of graph of type AdjList

which has a

pointer of type AdjListNode which is also a pointer.

Since *array member in Graph is a pointer to AdjList then why is

`graph->array[i]->head = NULL;`

not used ?

I know that

`.`

`somestructpointer -> itsmember`

is basically sugar coating

`(*somestructpointer).itsmember`

I don't understand what's happening. HELP.

Answer Source

`graph`

is a pointer.

`graph->array`

dereferences the above pointer to to get to the array variable.

`graph->array[i]`

uses array notation to reach a member at position `i`

.

The member we reach is of type `struct AdjList`

, which is not a pointer. It's a `struct`

. So a dot(`.`

) is appropriate.