克隆void *指向int的指针(Clone void* pointer to int)

系统教程 行业动态 更新时间:2024-06-14 16:52:52
克隆void *指向int的指针(Clone void* pointer to int)

我有这个功能的签名:

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

更多推荐

本文发布于:2023-04-05 12:25:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/6253d5dd047d270c944fd7d6ba7e33c7.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:指针   int   void   Clone   pointer

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!