【发布时间】:2020-03-28 23:27:59
【问题描述】:
我想从另一个结构中复制一个结构,如下所示:
#include <stdio.h>
#include <stdlib.h>
struct foo_struct{
int foo;
char *str;
};
static void foo(struct foo_struct *, struct foo_struct *);
void main(void) {
int i;
struct foo_struct *test = malloc(sizeof(struct foo_struct) * 5);
struct foo_struct *cpy_struct = NULL;
foo(test, cpy_struct);
cpy_struct->foo = 20;
//printf("%d\n", cpy_struct.foo);
free(test);
}
static void foo(struct foo_struct *test, struct foo_struct *cpy){
int i;
for(i = 0; i < 5; i++)
test[i].foo = i;
cpy = &test[2];
}
但是,当我修改此条目时:cpy_struct->foo = 20;,我遇到了分段错误。
当我没有使用struct foo_struct cpy_struct中的指针时,我修改了我的条目,但不是原始结构:
struct foo_struct cpy_struct = {0};
foo(test, &cpy_struct);
cpy_struct.foo = 20;
printf("%d\n", cpy_struct.foo); /* Display 20 */
printf("%d\n", test[2].foo); /* Display 2 */
/* ... */
static void foo(struct foo_struct *test, struct foo_struct *cpy){
int i;
for(i = 0; i < 5; i++)
test[i].foo = i;
*cpy = test[2];
}
如何复制这个结构来更新特定结构中的值?
谢谢。
【问题讨论】:
-
您需要将
cpy_struct的地址传递给foo()并在该函数中更新cpy,例如*cpy = &test[2]。在您的情况下,当foo()返回时,函数中更新的cpy中的值会丢失