Passing a pointer to a pointer in a c function by value

fid_table

- pointer to an array of pointers fid_list

.

I am trying to initialize fid_table

before NULL

in a separate function. I understand that fid_table is copied by value, but it is a pointer, so it shouldn't be a problem.

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

      

The function is fid_table_init

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 anyone clarify why this statement fails?

+3


source to share


2 answers


Define the function like this

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 a value, which is the function associated with the copy of the pointer. Therefore, any changes to the copy do not affect the original pointer.

Note that the parameters of a function are local variables. Thus, inside the function, you have allocated memory and assigned its address to a local variable of the function. The local variable is not assigned to the original pointer. After exiting the function, the local variables will be destroyed. The original pointer knows nothing what was done with its copy

+5


source


In a function fid_table_init

fid_table

, this is a local variable that is initialized with the value passed from the caller. The string malloc

changes the value of the local variable, it does not change the value fid_table

in the caller, so the calling code never sees the pointer returned from malloc

.

The easiest way to fix the code is to return the new pointer value from the function fid_table_init

and assign it fid_table

in the caller.

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

      




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

      

+5


source







All Articles