Max Rahm
Max Rahm

Reputation: 694

C struct into array of struct pointers compile error

I've got a linked list and I'm trying to make a temporary array to help me address each node while I build the rest of the structure, then I intend to free the array but it seems I can't store the address of the struct into a pointer array.

Here's a boiled down version of where I'm having problems:

vertex *vertexIndex = NULL;
vertex *vertexHead = NULL;
vertexHead = malloc(sizeof(vertex));
vertexHead->vertexNum = 5;
vertexIndex = malloc(sizeof(vertex*));
vertexIndex[0] = vertexHead;            //<<<<<<<<<<<  Error on this line
printf("%u\n", (vertexHead[0])->vertexNum);

main.c:72:19: error: incompatible types when assigning to type ‘vertex’ from type ‘struct vertex *’

Any help would be greatly appreciated.

EDIT

Here are the structs

struct edgeStruct {
    unsigned int edgeTo;
struct edgeStruct *nextEdge;
};
typedef struct edgeStruct edge;

struct vertexStruct {
    unsigned int vertexNum;
    edge *edgeHead; 
    struct vertexStruct *nextVertex;
};
typedef struct vertexStruct vertex;

Upvotes: 1

Views: 292

Answers (3)

Rohan
Rohan

Reputation: 53326

As the error message says, on that line you are trying to assign content of pointer to the pointer ie. assigning vertexHead which is vertex * to *vertexIndex (equivalent to vertexIndex[0] which are not compatible.

It will be better you post your code of definition of vertex so that people can suggest what should be done preferably.

Upvotes: 1

P.P
P.P

Reputation: 121387

vertexIndex is not an array of struct. It's just a struct pointer which is why you are getting the error.

If you want an array, declare an array: vertex

vertex *vertexHead[10]; //array of 10 pointers

Now, you'll be able to use it as you do now.

Upvotes: 1

Todd Li
Todd Li

Reputation: 3269

vertexIndex should be a pointer to a pointer, because you are using it as an array of pointers.

vertex **vertexIndex = NULL;

Upvotes: 1

Related Questions