简体   繁体   中英

C Void pointer as an argument

I'm trying to pass in something by address. In this case a char array but it could be anything.

void rickyHashTableAdd(rickyHashTable *table, char *key, void *value)
{
    rickyHashTableEntry entry;
    entry.key = strdup(key);    
    entry.value = value;
    table->entries[0] = entry;
}

int rickyHashTableGet(rickyHashTable *table, char *key, void *value)
{
    value = table->entries[0].value;
}

int main (void) 
{       
    void *val;
    val = "what up";
    rickyHashTableAdd(&symbolTable, "ok", val);
    void *val2;
    rickyHashTableGet(&symbolTable, "ok", val2);
    printf("result: %s\n", val2);   

}

When I check the value of 'value' inside the rickyHashTableGet function it is correct, but when I check in in main after the function has been called it's bad. It seems to not be setting to the right memory address. Why is this?

int rickyHashTableGet(rickyHashTable *table, char *key, void *value)
{
    value = table->entries[0].value;
}

This ignores the value that was passed. Sets value to something and then throws it away. This can't be right.

void *val2;
rickyHashTableGet(&symbolTable, "ok", val2);

This doesn't set val2 to anything, and thus passes a nonsense value to rickyHashTableGet . That can't be right.

You want:

int rickyHashTableGet(rickyHashTable *table, char *key, void **value)
{
    *value = table->entries[0].value;
}

That takes a pointer to a void * and makes it point to something.

And:

void *val2;
rickyHashTableGet(&symbolTable, "ok", &val2);

That passes the address of val2 to rickyHashTableGet , so it can set its value.

In your get routine, it should be void **get as the parameter and *value = table->entries[0].value; The call would then use &val2.

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