Tutorial :Why can I not assign interchangeably with two structs that have identical contents?



Question:

I'm trying to learn C and I've come across something weird:

struct  {    int i;    double j;  } x, y;    struct  {    int i;    double j;  } z;  

Here, you can see I created two structs that are identical in their elements.

Why is it that when I try to assign x = z it will generate a compile error but x = y does not? They have the same contents, so why can't I assign them back and forth with each other, regardless?

Is there any way I can make this so I can assign x = z? Or do they simply have to be the same struct.

Can any C gurus point me in the right direction?


Solution:1

They have the same content, but not the same type. If they are intended to be of the same type, simply typedef x z;. If they aren't the same thing, but just happen to contain the same fields, it's better to create a separate function that will assign the fields properly.


My usual style for declaring structs in C includes the typedef, so I forgot to mention it (sorry!). Here's the syntax:

typedef struct  {    int foo;    double bar;  } x;    /* Further down, if needed */  typedef x z;  


Solution:2

Making identically structured types the same is called "duck typing". This is done in some languages, but not in C.


Solution:3

The compiler does not calculate "type equivalence" between structs that may have the same structure, so as far as it is concerned, the second struct has nothing to do with the first one.

It can do x and y because they are declared at the same time.

Why are you redeclaring the struct ? You should probably typedef the struct once (e.g., in an H file) to make it an actual type, and then declare instances.

Here's a good tutorial on typedefs for structs.


Solution:4

struct mystruct  {    int i;    double j;    };    struct mystruct x, y;  struct mystruct z;  

If you intend to copy data between them, you must declare them with the same identity. You have two declarations, it doesn't matter they are equal for the compiler, they are two different structures, and the compiler is not supposed to detect their similarity.


Solution:5

C differentiates structs based on name, and if they're anonymous, then different structure definitions are different.

Anyhow, classic C doesn't allow x = z when x and z are structs -- is that an ANSI or a C99 addition? Anyhow, you should instead use

#include <string.h>  memcpy(&x, &z, sizeof(x));  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »