Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing a pointer to a pointer in c function by value

fid_table is a pointer to an array of fid_list pointers.

I am trying to initialize the fid_table to NULLs in a separate function. My understanding that fid_table is copied by value but it is a pointer so that should not be the problem.

fid_list **fid_table;
fid_table_init(fid_table);
assert(fid_table[0] == NULL);

The function fid_table_init is defined as follows:

void fid_table_init(fid_list **fid_table){
    fid_table = (fid_list **) malloc(HTABLE_SIZE * sizeof(fid_list *));
    for(int i = 0; i < HTABLE_SIZE; i++){
        fid_table[i] = NULL;
    }
}

Can someone elaborate on why this assertion fails?

like image 215
Keeto Avatar asked Aug 23 '26 14:08

Keeto


1 Answers

Define the function the following way

void fid_table_init(fid_list ***fid_table){
    *fid_table = (fid_list **) malloc(HTABLE_SIZE * sizeof(fid_list *));
    for(int i = 0; i < HTABLE_SIZE; i++){
        ( *fid_table )[i] = NULL;
    }
}

And call it like

fid_table_init( &fid_table );

In the original function the pointer is passed by value that is the function deals with a copy of the pointer. So any changes of the copy do not influence on the original pointer.

Take into account that function's parameters are its local variables. So inside the function you allocated a memory and assigned its address to a local variable of the function. It is the local variable that was assigned not the original pointer. After exiting the function its local variables will be destroyed. The original pointer knows nothing what was done with its copy

like image 116
Vlad from Moscow Avatar answered Aug 26 '26 03:08

Vlad from Moscow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!