C语言 复制指针中的数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5976393/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 08:37:56  来源:igfitidea点击:

Copying data in pointers

cpointers

提问by system

How does one copy the data that is pointed to by another pointer?

如何复制另一个指针指向的数据?

I have the following

我有以下

void *startgpswatchdog(void *ptr)
{
    GPSLocation *destination;
    *destination = (GPSLocation *) ptr;

Will this do this correctly?

这会正确地做到这一点吗?

I free the data that is passed into thread after passing it, so I need to copy the data.

我把传入线程后的数据释放了,所以我需要复制数据。

回答by Mihran Hovsepyan

If you want to copy data you should allocate new memory via malloc, then copy your memory via memcpy.

如果你想复制数据,你应该通过 分配新的内存malloc,然后通过复制你的内存memcpy

void *startgpswatchdog(void *ptr)
{
    GPSLocation *destination = malloc(sizeof(GPSLocation));
    memcpy(destination, ptr, sizeof(GPSLocation));
}

回答by system

You can do it if the pointer you ae copying to actually points at something:

如果您复制到的指针实际上指向某个东西,您可以这样做:

void *startgpswatchdog(void *ptr)
{
    GPSLocation *destination = malloc( sizeof( GPSLocation ) );
    *destination = * (GPSLocation *) ptr;
}

or perhaps better:

或者更好:

void *startgpswatchdog(void *ptr)
{
    GPSLocation destination;
    destination = * (GPSLocation *) ptr;
}

回答by yossi

you need to allocate memory before you assign to the address pointed by the pointer. why do you need a pointer here ? why not use

您需要在分配给指针指向的地址之前分配内存。为什么这里需要一个指针?为什么不使用

void *startgpswatchdog(void *ptr)
{
GPSLocation destination;
destination = (GPSLocation) *ptr;
}

and later if you need this variable address just use

稍后如果您需要此变量地址,请使用

&destination

just dont forget its a local variable :)

只是不要忘记它是一个局部变量:)