tags:

views:

374

answers:

5

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?

+11  A: 

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;
John Millikin
When you say typedef x z; how does that work? Can you elaborate just a little on what you mean so I could typedef the struct and create instances of it?
Mithrax
`typedef struct x z`
Ismael
+8  A: 

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

Don Reba
Never heard it called that.
Blank Xavier
"If it walks like a duck and quacks like a duck, I would call it a duck."
Albert
+5  A: 

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.

Uri
Thank you for the tutorial!
Mithrax
+3  A: 
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.

Juliano
A: 

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));
ephemient