简体   繁体   English

使用memcpy复制数据

[英]Copying data using memcpy

I am doing a memcpy of clsf_ptr to upclsf 我正在为upclsf做一个clsf_ptr的memcpy

memcpy(&upclsf, &clsf_ptr, sizeof(struct classifier));

while debugging using gdb i checked the memory address of upclsf when i did print &upclsf i got 在使用gdb进行调试的时候,我检查了upclsf的内存地址,当时我打印了up&upclsf

(gdb) p &upclsf
$1 = (struct classifier **) 0xbffff184

when i did print upclsf i got 当我打印upclsf我得到了

(gdb) p upclsf
$2 = (struct classifier *) 0x2e312e31

which is the address here i am not able to understand, here upclsf is an instance of the structure classifier 这里的地址是我无法理解的,这里upclsf是结构分类器的一个实例

GDB disagrees — upclsf is not a struct classifier , it is a pointer. GDB不同意 - upclsf不是struct classifier ,它是一个指针。 Note that the two answers have different types. 请注意,这两个答案有不同的类型。 The first one ( &upclsf ) is struct classifier ** , the second one ( upclsf ) is struct classifier * . 第一个( &upclsf )是struct classifier ** ,第二个( upclsf )是struct classifier * Here is the memory layout: 这是内存布局:

addr 0xbffff184 / upclsf: pointer to 0x2e312e31

addr 0x2e312e31 / *upclsf: (structure data)

You want to change your memcpy to: 您想将memcpy更改为:

memcpy(upclsf, &clsf_ptr, sizeof(struct classifier));

Or possibly: 或者可能:

memcpy(upclsf, clsf_ptr, sizeof(struct classifier));

Note that memcpy will wantonly destroy data and is not type-safe! 请注意, memcpy将大肆破坏数据,并且不是类型安全的! Therefore you have to be extra careful when you use it to ensure that the types you give it are correct. 因此,在使用它时必须格外小心,以确保您提供的类型是正确的。 I suggest defining the following function: 我建议定义以下功能:

static inline void
classifier_copy(struct classifier *dest, struct classifier const *src)
{
    memcpy(dest, src, sizeof(*dest));
}

This will catch type errors. 这将捕获类型错误。 I make one of these for any structure I copy more than once or twice. 对于我复制一次或两次以上的任何结构,我都会制作其中一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM