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 struct
s 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?
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:
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.
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.
Making identically structured types the same is called "duck typing". This is done in some languages, but not in C.
C differentiates
struct
s based on name, and if they're anonymous, then different structure definitions are different.Anyhow, classic C doesn't allow
x = z
whenx
andz
are structs -- is that an ANSI or a C99 addition? Anyhow, you should instead use