Eyzuky Eyzuky - 1 year ago 92
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.

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download