3

If i have these structures:

struct rec {
 int key;
 double value;
};

struct node {
 struct rec record;
 struct node *next;
};

and I have to copy the values of the fields of an item struct rec *r into an item struct node *n,

can i do this?

n->record.key = r->key;
n->record.value = r->value;
4

3 回答 3

5

是的,您可以一次复制struct一个字段。您也可以一次性完成:

struct rec *r = ...;
struct node *n = ...;
n->record = *r; // Copies the content of "r" into n->record

这样做的好处是不必在每次修改struct rec.

于 2013-09-04T16:11:56.813 回答
2

由于该rec结构仅包含基本类型的字段,因此这样做是完全有效且合理的:

n->record = *r;

在这种情况下,这相当于分别复制keyvalue字段:

n->record.key = r->key;
n->record.value = r->value;
于 2013-09-04T16:13:33.303 回答
-1
n->rec.key = r->key;
n->rec.value = r->value;

正确但更好的是:

memcpy(&n->rec, r, sizeof n->rec);

现在您可以在不更改现有代码的情况下使用新字段扩展 struct rec

于 2013-09-04T16:17:54.480 回答