I have a struct:
struct points{
int i;
int x;
int y;
};
I made an array of the struct and named it temp. Then I made another and named it pt. Suppose I put some contents to temp. How can I copy the elements of temp to pt?
Here's my code of memcpy and the compiler says it's segmentation fault. 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
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.
Note that your allocation of pt
is a variable length array if i
is a variable. This can be dangerous and lead to a stack overflow if i
is getting too large. So if you plan to use large arrays here, better use 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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.