我想将存储在结构中的一些数据复制到另一个.下面的代码是否有效?是否推荐?
#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));
Run Code Online (Sandbox Code Playgroud)
它是否有效取决于你打算做什么.它复制从比特t1到t2,包括填充,但当然副本的指针,而不是指向的值.
如果你不关心填充位 - 你为什么要这么做 - 一个简单的任务
Test t2 = t1;
Run Code Online (Sandbox Code Playgroud)
就是你需要复制指针.
如果希望重复和复制指向的值,则代码和简单赋值都不起作用.
要复制指向的内存块,首先,您必须知道它们的大小.没有(便携式)方法从指针中找出指向内存块的大小.
如果大小由a给出#define,您当然可以重用它,否则您需要在某处存储已分配块的大小.
但由于新分配的内存块具有与要复制的块不同的地址,因此我们无需将指针值复制t1到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);
Run Code Online (Sandbox Code Playgroud)