Suppose we have an array of pointers called int *weights[]
in structure Graph
and we initialize it
int CreateGraph(Graph *G, int vexs){
G->n = vexs;
for(int i = 0; i < G->n; i++){
G->weights[i] = (int*)malloc(sizeof(int)*G->n);
}
for(int i = 0; i < G->n; i++){
for (int j = 0; j<G->n; j++) {
G->weights[i][j] = j;
}
}
return 1;//just for test
}
also we have a function to show the graph
void show(Graph G){
for(int i = 0; i<G.n; i++){
for (int j = 0; j<G.n; j++) {
printf("%d",G.weights[i][j]);
}
}
}
in main
Graph *g = (Graph *)malloc(sizeof(Graph));
CreateGraph(g, 3);
show(*g);
it crashed and xcode said EXC_BAD_ACCESS (code=1, address=0x0),but i have another worked version of function show
void success_show(Graph *G)
Graph
typedef struct {
int n;
int *weights[];
}Graph;
Question:
- What's the difference between using Graph *G and Graph G as function parameter here
show(Graph G) success_show(Graph *G)
. - is it ok to initialize array of pointer using
G->weights[i] = (int*)malloc(sizeof(int)*G->n);