简体   繁体   中英

Changing a pointer inside a function

This function is resizing a hash table, my problem is that after my resize function is done messing with the temptable, i set table=temptable at the end of my resize function, while its within the function is has the correct address... but as soon as we go back into the main function the table pointer never got updated. I understand this can be solved by doing pass by reference.

However, I am not allowed to change anything in main at all, including how resize is called. Im also not allowed to change the resize_hash function arguments at all either. All im allowed to change is the contents within the function.

The struct for the hash table:

typedef struct hash_table_ {
    int size;
    hash_entrys **buckets;
    void (*print_func)(void *);
} hash_table, *Phash_table;

The resize function call from main:

resize_hash(table, HASH_SIZE + i*250);

Function code:

void resize_hash(Phash_table table, int size){
    int h=0;
    Phash_table temptable;
    hash_entrys *head_re, *cur_re;
    temptable = new_hash(size,table->print_func);

    for(h=0;h<(table->size);h++){
        head_re=table->buckets[h];
        if(head_re!=NULL){
            for(cur_re=head_re;cur_re!=NULL;cur_re=cur_re->next){
                insert_hash(temptable,cur_re->key,cur_re->data);
            }
        }   
    }


    table=temptable;
    free(temptable);
}

A called function can't change its arguments directly. The only ways it can convey information are by returning something (so you could make resize_hash return temptable, that's probably the best solution) or by modifying something it has the pointer to. You can't modify the pointer table because resize_hash doesn't have a pointer to the pointer table, but you can modify the hashtable the pointer table points to. In particular, you could realloc the original hashtable's hash_entrys and then change pointers and size within the struct accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM