Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C- Structure within structure

Tags:

c

structure

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;
like image 827
SegFault Avatar asked Jan 26 '26 23:01

SegFault


2 Answers

Yes, you can make a copy of your struct one field at a time. You can also do it in a single shot:

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

Doing it that way has the advantage of not having to revisit the copying code each time you modify the structure of struct rec.

like image 56
Sergey Kalinichenko Avatar answered Jan 29 '26 12:01

Sergey Kalinichenko


Since the rec structure contains only fields of basic types, it is perfectly valid and reasonable to do:

n->record = *r;

which in this case is equivalent to copying key and value fields separately:

n->record.key = r->key;
n->record.value = r->value;
like image 37
LihO Avatar answered Jan 29 '26 13:01

LihO