1

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.

Garf365
  • 3,619
  • 5
  • 29
  • 41
Eyzuky
  • 1,843
  • 2
  • 22
  • 45

1 Answers1

5

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);
}
Ishay Peled
  • 2,783
  • 1
  • 23
  • 37