Search code examples
cpointersclone

Clone void* pointer to int


I have this signature of a function:

void* cloneInt(const void* i);

This int represents a key for a hash function. I need to have this clone function as it is in my API for a generic implementation of a hash table (this function is a part of the int implementation, this function will be forwarded as a pointer to a function that my generic implementation will use). But I am having a problem understanding: how can you clone an int? I need to return a pointer that will point on the same value of int, but a different place in the memory. This got me very much confused.


Solution

  • This will work:

    #include <stdio.h>
    #include <stdlib.h>
    
    void* cloneInt(const void* i)
    {
        int *myInt = malloc(sizeof(int));
        *myInt = *(int*)i;
        return myInt;
    }
    
    int main(int argc, char** argv)
    {
        int i=10;
        int *j;
        j = cloneInt(&i);
        printf("j: %d i: %d\n", *j, i);
        free(j);
    }