1

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;
2
  • Can we see the declarations of vertexHead, and vertexIndex ? Commented Sep 14, 2012 at 18:27
  • Suspect the issue is with sizeof(vertex*)? Although you seem to be populate an array by generating a pointer? I'm trying to understand what you are trying to do, unsuccessfully?! Commented Sep 15, 2012 at 6:48

3 Answers 3

1

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

vertex **vertexIndex = NULL;
Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

I'm trying to declare an array in such a way that I can use realloc on it later. Are "vertex *vertexIndex[10];" and "vertexIndex = malloc(sizeof(vertex*) * 10);" not equivalent?
@user1671981 First is allocated on stack and 2nd is allocated on heap. You can use either one depending on your need. Stack allocated variables are alive only in the scope they are declared.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.