0

I have some issue with programming in C. I have a structrure, that goes like

 typedef struct Hash_Funct{
char* name;             
Var_Table * List_of_Variables;   ///pointer to list of variables
} Hash_Funct;

And in certain point of code, I want to inicialize the structure with:

    Hash_Funct tmp = (Hash_Funct*) malloc(sizeof(Hash_Funct));
    tmp->name=name;
    Init_ID_Table(tmp->List_of_Variables);

Where the Init_ID_Table(); is defined as:

void Init_ID_Table(Var_Table *table){
    table = (Var_Table*) malloc ( sizeof(Var_Table) );
    for(int i=0; i< SIZE;i++){
        (*table)[i] = NULL;
    }
}

However, at the end of this code, it doesnt seems that the Init_ID_Table() had any affect on the * List_of_Variables pointer (which should now point onto a table of size SIZE and have all its elements set to NULL). Can anyone at least tell me what is going on if not how to change it to work as expected?

Thank you very much, Adam

Adam
  • 23
  • 3

1 Answers1

1

Variables are passed by value, assigning to the parameter variable in the function has no effect on the caller's variable.

You need to pass a pointer to the struct member, and indirect through it to modify the caller's variable.

void Init_ID_Table(Var_Table **table) {
    Var_Table *temp_table = malloc ( sizeof(Var_Table) );
    for (int i = 0; i < SIZE; i++) {
        temp_table[i] = NULL;
    }
    *table = temp_table;
}

Then you would call it this way:

Init_ID_Table(&(tmp->List_Of_Variables));
Barmar
  • 741,623
  • 53
  • 500
  • 612