0

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);
potato
  • 333
  • 1
  • 10

1 Answers1

3

You have to allocate memory for G->weights.

G->weights = (int**) malloc(sizeof(int*)*G->n);

And then allocate memory for each individual pointer element.

for(i=0; i<G->n; i++)
{
    G->weights[i] = (int*) malloc(sizeof(int)*<entersize>);
}
awakened
  • 192
  • 9
  • 1
    Please see [Do I cast the result of malloc?](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – Bo Persson Mar 13 '18 at 11:07