I am trying to make an array of structures in which each array elements itself points to another structure of the same type. In order to better explain the problem, I have made a schematic for it! The names of the variables are according to the code (shown below)
But I am getting an error while I am freeing the memory! Can someone provide some hints for solving this! Thanks.
Error:
tempCodeRunnerFile.c:36:42: error: member reference type 'Vertex *' (aka 'struct Node *') is a pointer; did you mean to use '->'?
Vertex* ptr = (*(vertexarray+ i)).next;
~~~~~~~~~~~~~~~~~~~^
->
tempCodeRunnerFile.c:57:14: warning: incompatible pointer types passing 'Vertex [4]' to parameter of type 'Vertex **' (aka 'struct Node **') [-Wincompatible-pointer-types]
finalize(vertexarray);
^~~~~~~~~~~
tempCodeRunnerFile.c:30:24: note: passing argument to parameter 'vertexarray' here
void finalize(Vertex** vertexarray){ // free the dynamic memmory
^
1 warning and 1 error generated.
Code:
#include <stdio.h>
#include <stdlib.h>
// Data structure to store a linked list node
typedef struct Node
{ int data;
struct Node* next;
}Vertex;
Vertex* initialize(); //Vertex** vertexarray
void finalize(Vertex** vertexarray);
Vertex* initialize(){ // initialise the elements inside the array
Vertex* node = (Vertex*)malloc(sizeof(Vertex));
if(node ==NULL){
printf("Error in initialising"); // If node cannot be created due to memmory issues.
return NULL; // listhead is NULL
}
else{
node->data = -1; // The initial node is empty (contains data value -1, symbolising empty).
node->next = NULL; // The list at the time of initialisation is empty and hence no node to further point on.
}
return node;
}
void finalize(Vertex** vertexarray){ // free the dynamic memmory
int i;
for (i=0; i<4;i++){ // free all the memmory
Vertex* ptr = (*(vertexarray+ i)).next;
Vertex* tmp;
while( ptr!= NULL) // Termination condition: At the end, the pointer is not pointing to any node, but a NULL value
{
tmp = ptr; // make tmp the current node starting from listhead.
ptr = ptr->next; // update the pointer to the next pointer
free(tmp); // free the previous pointer
}
}
}
int main(void)
{
Vertex vertexarray[4];
int i;
for (i=0; i<4;i++){
vertexarray[i].next = initialize();
}
finalize(vertexarray);
return 0;
}

*(vertexarray+ i)tovertexarray[i], or add parenthesis around it, in order to fix the operator precedence issue in your code:(*(vertexarray+ i)).next. Nice drawing BTW.*(vertexarray+ i).nexttovertexarray[i].next;(or(*(vertexarray+ i)).next) won't fix anything, including the compilation problem. All those are synonymous with what you started with. There isn't a precedence issue there whatsoever.