我有这个功能的签名:
void* cloneInt(const void* i);这个int代表一个散列函数的关键字。 我需要这个克隆函数,因为它在我的API中用于散列表的通用实现(该函数是int实现的一部分,该函数将作为指向我的通用实现将使用的函数的指针) 。 但我有一个问题的理解:你如何克隆一个int ? 我需要返回一个指向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.
最满意答案
这将工作:
#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); }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); }更多推荐
发布评论