简体   繁体   English

如何在C中的Struct中使用memcpy?

[英]How to use memcpy in Struct in c?

I have a struct: 我有一个结构:

struct points{
int i;
int x;
int y;
};

I made an array of the struct and named it temp. 我对结构进行了数组并将其命名为temp。 Then I made another and named it pt. 然后我做了另一个,并命名为pt。 Suppose I put some contents to temp. 假设我将一些内容放入了临时文件。 How can I copy the elements of temp to pt? 如何将temp的元素复制到pt?

Here's my code of memcpy and the compiler says it's segmentation fault. 这是我的memcpy代码,编译器说这是分段错误。 Help please. 请帮助。

#define MAX_POINTS 400
struct points temp[MAX_POINTS];
/* Some code to input elements to array temp */
struct points pt[i]; /* array of struct with i elements*/
memcpy(&pt, &temp, sizeof (temp));

You have to be careful to only copy the size of the smaller of the two, here I suppose that i < MAX_POINTS 您必须注意只复制两者中较小的一个,在这里我想i < MAX_POINTS

memcpy(pt, temp, sizeof pt);

Also as others already said the & are not correct. 也正如其他人已经说过的, &不正确。 You need a pointer to the first element, that is &pt[0] for example, or just pt as the array decays to &pt[0] in that context. 需要一个指针的第一个元素,即&pt[0]例如,或只是pt作为阵列衰减到&pt[0]在这方面。

Note that your allocation of pt is a variable length array if i is a variable. 请注意,如果i是变量,则pt的分配是可变长度数组。 This can be dangerous and lead to a stack overflow if i is getting too large. 如果i变得太大,这可能很危险并导致堆栈溢出。 So if you plan to use large arrays here, better use malloc : 因此,如果您打算在这里使用大型数组,最好使用malloc

struct points* pt = malloc(sizeof(struct points[i]));
memcpy(pt, temp, sizeof(struct points[i]);

Unfortunately then, you can't use sizeof pt for the memcpy . 不幸的是,您不能将sizeof pt用于memcpy

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

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