Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Structures and unions

Status
Not open for further replies.

NotBear

Programmer
Jun 22, 2003
11
AU
Hi,
I am learning about unions. I have the following code declaring a union of 2 structures, and pointers to the structures. How can I assign a pointer of the structure to the structure in the union ?

typedef struct {
char A[100]
} Struct1;

typedef struct {
char B[100]
} Struct2;

typedef union {
Struct1 s1;
Struct2 s2;
} MyUnion;

struct Struct1 * sp1;
struct Struct2 * sp2;
MyUnion union1;

main()
{...
/* Is this correct ?? */
union1.s1=*sp1;
...
}

I am getting "dereferencing pointer to incomplete type" compile errors with the above assignment.
 
1. char A[100]; - semicolon missed (char B[100]; too).
2. Struct1* sp; - not struct Struct1!!! Struct1 is defined as type alias by typedef. Your struct Struct1 construct defines a new and incomplete type (in C name after struct keyword is defined in a separate namespace).
3. OK, union1.s1 is a reference to s1 member of union. But where is sp1 pointer initialization?
4. Usually (traditionally) all uppercase names used for macros only...
 
Number 2 was it. If I set my pointer to the structure with Struct1 *sp1, then union1.sp1 works.
 
More (step by step) explanation:
Code:
typedef struct
{
  char a[100];
} Struct1;
Now we have type alias for this struct. We must declare variables of this type (and pointer to this type) as:
Code:
Struct1  s1; /* Not struct Struct1 !!! */
Struct1* sp1;
When we declare:
Code:
struct Struct1  anyvar; /* or... */
struct Struct1* anyptr;
we introduce a new type named struct Struct1.
The 1st and the 2nd Struct1 are different things (they lives in separate name spaces)!

New type struct Struct1 is not a complete type (there are no this struct body declaration. You may pass pointers to this type but can't dereferencing them (no known members, no real structure in this scope).

Well, now you may play with unions as you wish - it's so simple C constuct (and so low-level, and error-prone)...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top