Home > front end >  Assigning one struct variable to the another varible of a same type which is in different struct in
Assigning one struct variable to the another varible of a same type which is in different struct in

Time:09-03

Can we assign one variable from a structure to another variable of a same type which is in a different struct, directly in C ? Such as:

struct Test1 
{
   inx x1;
   int y1;
}

struct Test2
{
   int x2;
   int y2;
}

void trialStruct(Test2& origin2)
{
   Test1 origin1;
   origin1.x1 = origin2.x2;
   origin2.y1 = origin2.y2
}

CodePudding user response:

Can we assign one variable from a structure to another variable of a same type which is in a different struct, directly in C ?

Yes, the type of origin1.x1 and origin2.x2 is same(both are int) and we can assign origin2.x2 to origin1.x1 as you've done in your example.


Note also that instead of assigning individual members, you can use aggregate initialization to initialize the data member in your particular example as shown below:

void trialStruct(Test2& origin2)
{
   //aggregate initialization 
   Test1 origin1{origin2.x2, origin2.y2};
}
  •  Tags:  
  • c
  • Related