0

In the following code, can we copy yy to xx? If not, is there another way? Do we have to use pointer or something else?

typedef unsigned int UINT32
typedef struct
{
    UINT32 a : 4; 
    UINT32 b: 2;      
    UINT32 c: 2;
    UINT32 d: 4;
    UINT32 e: 4;
    UINT32 f: 8; 
    UINT32 g: 8;
}Word;

Word *xx , *yy;
xx = yy;
xx->a = 1; 

4 Answers4

0

Of course you can assign one structure to each other. Every member would be copied.

In your examples, *xx = *yy is equivalent to:

xx->a = yy->a;
xx->b = yy->b;
//...
xx->g = yy->g;

notice that you must copy *yy in *xx, not the pointer yy into the pointer xx. Notice also that you didn't initialize the pointers, nor the structures. You should go something like

Word a, b;
b.a = ...;
b.b = ...;
...
b.g = ...;
Word* xx = &a;
Word* yy = &b;
*xx = *yy; //equivalent to a = b;

You must pay attention to struct containing pointers: the value of the pointer is copied in that case, hence the underlying object, if any, is the same one. Depending on the semanthics of your code, this could or could not be what you mean.

Stefano Falasca
  • 8,837
  • 2
  • 18
  • 24
0

I would do it simply like this:

#include <string.h>

Word A = { 4,2, 2,4,4,8,8};
Word B;
memcpy( &A, &B, sizeof(Word));

simple and effective.

Edit: And even simpler is:

Word A = { 4,2, 2,4,4,8,8};
Word B = A;
hetepeperfan
  • 4,292
  • 1
  • 29
  • 47
0

your code copy the pointer so that xx and yy points to the same object. if you would use structs (and not pointers) the = operator would by exactly as using memcpy

Here is the 2 pointers in the watch after the copy. Notice the same address Here is the 2 pointers in the watch after the copy. Notice the same address

asafrob
  • 1,838
  • 13
  • 16
0

You can try using the normal objects. Data cannot be initialized inside a structure implicitly in c. A object has to be created and data has to be fed in.

If the structure looks like this

typedef unsigned int UINT32;
struct Word{
  UINT32 a;
  UINT32 b;
  UINT32 c;
  UINT32 d;
 };

Without using pointers:

Word xx , yy={0,1,2,3};
xx = yy;
xx.a = 10;
yy.b = 100; 
printf("%d -- %d -- %d -- %d",yy.a,yy.b,yy.c,yy.d); // 0 -- 100 -- 2 -- 3 
printf("%d -- %d -- %d -- %d",xx.a,xx.b,xx.c,xx.d); // 10 -- 1 -- 2 -- 3 

Here xx and yy are different objects created for Word. yy object data is copied to xx. When making changes to element of xx will not affect yy data because both are differnet objects.

When using pointers:

 struct Word *xx;
 struct Word *yy=malloc(sizeof(struct Word));
 yy->a=0;
 yy->b=1;
 yy->c=2;
 yy->d=3;
 xx=yy;
 xx->a = 10;
 yy->b = 100; 
 printf("%d -- %d -- %d -- %d",yy->a,yy->b,yy->c,yy->d); // 10 -- 100 -- 2 -- 3 
 printf("%d -- %d -- %d -- %d",xx->a,xx->b,xx->c,xx->d); // 10 -- 100 -- 2 -- 3 

Here you have allocated memory for xx and initialized data to it. Both xx and yy point to a same memory location so changing data in either xx or yy will affect both.

Amarnath Krishnan
  • 1,253
  • 1
  • 9
  • 12