我想将存储在结构中的一些数据复制到另一个结构中。下面的代码有用吗??推荐还是不推荐?
#define SIZE 100
struct {
int *a;
int *b;
} Test;
Test t1;
t1.a = malloc(SIZE);
t1.b = malloc(SIZE);
Test t2;
memcpy(t2,t1,sizeof(Test));
它是否有效取决于您打算做什么。t1
它从to复制位t2
,包括填充,但当然它复制指针,而不是指向的值。
如果你不关心填充位 - 为什么你应该 - 一个简单的分配
Test t2 = t1;
是您复制指针所需的全部内容。
如果您希望复制和复制指向的值,您的代码和简单的赋值都不起作用。
要复制指向的内存块,首先必须知道它们的大小。没有(便携式)方法可以从指针中找出指向的内存块的大小。
如果大小由 a 给出#define
,您当然可以重用它,否则您需要将已分配块的大小存储在某处。
但是由于新分配的内存块与要复制的块具有不同的地址,我们根本不需要复制指针 vlaues from t1
to t2
。
Test t2;
t2.a = malloc(SIZE); /* be aware that this is bytes, not number of ints */
t2.b = malloc(SIZE);
if (t2.a == NULL || t2.b == NULL) {
/* malloc failed, exit, or clean up if possible */
fprintf(stderr,"Allocation failure, exiting\n");
exit(EXIT_FAILURE);
}
/* malloc was successful in both cases, copy memory */
memcpy(t2.a, t1.a, SIZE);
memcpy(t2.b, t1.b, SIZE);