简体   繁体   中英

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;

vertexIndex应该是指向指针的指针,因为您将它用作指针数组。

vertex **vertexIndex = NULL;

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM