views:

62

answers:

4

Hi

I have following problem:

I have one global structure that has many structures inside. Now I want one of the substructures taken out and stored in some other structure.

typedef struct 
{
  int a;
}A;

typedef struct
{
 int b;
}B;

typedef struct 
{ 
 A dummy1;
 B dummy2;
} C;

I want to declare fourth structure that extracts A from C. I did my memcpy, is it only way?

Help will be very appreciated

Thanks Huzaifa

A: 

Should just be able to grab the reference of dummy1.

typedef struct { A dummy1; } D;

C var1;
D var2.dummy;
(*var2.dummy) = &var1.dummy1;
Suroot
It is throwing compilation error.'dummy' : is not a member of 'D' for ((*var2.dummy) = )syntax error : missing ';' before '.' for ( D var2.dummy;)
qrdl
-1: It's just `C var1; D var2; var2.dummy1 = var1.dummy1;`.
Oli Charlesworth
+1  A: 

You can assign structures. So:

typedef struct
{
    A blah1;
    B blah2;
    /* Other members here */
} D;

C c;
D d;
...
d.blah1 = c.dummy1;

is totally fine.

Oli Charlesworth
A: 

Can I ask why you're doing it the way you're doing it? There's nothing wrong with anonomous structs as you've declared them. However, with named constructs you'd follow the D-R-Y principle better (Don't Repeat Yourself):

struct myObject {
    int a;
    int b;
}

and then typedef them:

typedef myObject A;

so that you can have multiple copies of the same data type floating about. Then all you need to do to get at the value contained within:

A foo;
A bar;

foo.a = bar.a;

and that's it!

wheaties
A: 

Use a pointer to the struct you need:

int main() {
C c;
c.dummy1.a = 10;
c.dummy2.b = 20;

A *a;

a = &c.dummy1;

printf("%d\n", a->a);

return 0;

}

Tiago Natel