Eyzuky Eyzuky - 7 months ago 45
C Question

Clone void* pointer to int

I have this signature of a function:

void* cloneInt(const void* i);

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
? I need to return a pointer that will point on the same value of
, but a different place in the memory. This got me very much confused.


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);