Hey guys! I've always looked through this forum but I never registered until just now because I'm having some issues with a program of mine and I figured I could try asking around here..
First, here's my section of the code in question:
-------------------------------------------------------------
Code:
typedef struct GraphHelp{
int color;
int parent;
int source;
ListRef neighbors;
}GraphHelp;
typedef GraphHelp* GraphHelpRef;
typedef struct Graph{
int order;
int size;
int BFSsource;
GraphHelpRef *graph;
}Graph;
/*** Constructors-Destructors ***/
GraphRef newGraph(int n){
int i=0;
GraphHelpRef *array = (GraphHelpRef *)malloc(n * sizeof(GraphHelpRef));
GraphRef G = (Graph*)malloc(sizeof(GraphRef) * n);
if(!G){
printf("error allocating memory for Graph.\n");
exit(1);
}
for (i=0; i<n;i++){
GraphHelpRef temp = malloc(sizeof(GraphHelp));
temp->color = i;
temp->parent=NIL;
temp->source = NIL;
temp->neighbors = newList();
printf("%d",i);
array[n]=temp;
printf(" done initializing\n");
}
G->graph = (GraphHelpRef *)&array[0];
G->BFSsource=NIL;
G->order=n;
G->size=0;
return G;
}
-------------------------------------------------------------
ListRef is another ADT I made, and is 100% functional. it's initialized by the newList() function, as shown above. GraphRef is declared in my header file.
GraphHelp was my way of giving up on trying to fit 4 arrays into one structure..as that was causing me issues too.. all the variables in GraphHelp can be moved back to Graph but they all have to be arrays. I couldn't figure out how to make 4 dynamic arrays in my own struct so I just did what is above as a means of "simplifying" things.
So...my issue is with the newGraph function... I am certain that I am making a mess of the pointers, memory allocation, and arrays because my program will give me segmentation faults whenever I try writing to:
(some GraphRef)->graph[x]->(anything).
I've tried everything but I cant seem to figure out how to do this correctly.. can anybody help find my mistake/help me correct it? I would appreciate any input very much!! :-)
If you have any questions, please don't hesitate to ask me.