0

I have the following struct:

typedef struct Graph {
  Vertex* x;
  struct Graph* next;
  int numElts;
}Graph;

And the following code:

 void initialize(Graph *x){
 x=malloc(sizeof(Graph));
 x->size=0;

}

But for some reason the size is later evaluated to not be zero after this call and this call alone on an uninitialized graph object. Is this an issue with pass by value vs. pass by reference? If so, how can this be fixed so that the struct's field is actually modified?

CMonster
  • 1
  • 1
  • 4
    `void initialize(Graph **x){ *x=malloc(sizeof(Graph)); (*x)->numElts=0; (*x)->x=NULL; (*x)->next=NULL; }` , at Caller side `Graph *x; initialize(&x);` – BLUEPIXY Oct 17 '17 at 04:16
  • 1
    You're only modifying the local copy of `x`. That has no effect on the caller. Remember, C uses call by value, not call by reference. There are two ways to fix it: (1) Add a level of indirection, passing the address of `x`, or (2) return `x` so that the caller can update its copy. – Tom Karzes Oct 17 '17 at 05:17
  • 3
    Also, a`Graph` has no member named `size`. – Tom Karzes Oct 17 '17 at 05:23
  • or do: `Graph* initialize(){ Graph* x=malloc(sizeof *x); x->numElts=0; x->x = NULL; x->next=NULL; return x;}` and use like: `Graph* x = initialize();` – Support Ukraine Oct 17 '17 at 05:39

0 Answers0