i have an assignment that involves creating a Graph ADT. within this i need to have an array of Lists.
my List ADT is basically a doubly linked list with certain functionality. to create a new you call the function:
ListRef newList();
NOTE: ListRef is defined as "typedef struct List* ListRef". i.e., its just a handle/pointer to a List structure.
the problem is that you don't know the size of the graph until run time since you create a new one with the function:
GraphRef newGraph( int n );
where n is the number of vertexes in the graph (and thus the size of the array of List ADTs) and a GraphRef is just a pointer to a Graph structure.
i'm trying to do something like this:
struct Graph{
.
.
ListRef* list_array;
.
.
}
GraphRef newGraph( int n ){
GraphRef G = malloc(sizeof(Graph));
ListRef L[n];
.
.
for( i=0; i%26lt;n; ++i){
L[i] = newList();
}
G-%26gt;list_array = L;
.
.
}
But this results in no Lists being created (they are NULL) and then a core dump. what is wrong?
Creating an array of structures within another strucure in C.?
I think that the problem is that your ListRef array is being defined on the stack in the function newGraph(int n).
Once the function scope is over, G-%26gt;list_array will be pointing to a location that it doesn't own, and the first operation that it performs on it will cause a core dump.
What you need to do instead is to create your G-%26gt;list_array using malloc:
G-%26gt;list_array = (ListRef)malloc(n*sizeof(ListRef));
and then continue as before.
Hope this helps.
P.S. Interesting problem by the way :).
kudzu
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment