Week 13
Week 13
C STRUCTURES,
UNIONS
C How to Program, 8/e, GE
OBJEC T I V E S
Access struct members.
◦ Structures are derived data types—they’re constructed using objects of other types.
Consider the following structure definition
struct card { Structure tag
char *face;
char *suit; };
• A database is a collection of information subdivided into records. A record is a collection
of information of one data object (e.g., ID, name, and age of a student).
• C allows us to define a new data type (called structure type) for each category of a
structured data object.
OPERATIONS THAT CAN BE PERFORMED ON STRUCTURES
Structures can be initialized using initializer lists as with arrays. To initialize a structure,
follow the variable name in the definition with an equals sign and a brace-enclosed,
comma- Separated list of initializers. For example, the declaration
passing a pointer to a
structure.
TYPEDEF
◦ The keyword typedef provides a mechanism for creating synonyms (or aliases) for
previously defined data types. Names for structure types are often defined with typedef
to create shorter type names. For example, the statement
typedef struct card Card;
◦ defines the new type name Card as a synonym for type struct card. C programmers often
use typedef to define a structure type, so a structure tag is not required. For example, the
following definition creates the structure type Card without the need for a separate
typedef statement
typedef struct { char *face; char *suit; } Card;
struct card {
char *face;
char *suit; };
int main(void)
struct card B ;
};
=======================================================================
=======================
typedef struct {
char *face;
char *suit;
} Card;
int main(void)
{
Card B ;
}
OPERATOR
PRECEDENCE
IN STRUCT
TYPE
COMPONENT
SELECTION
OPERATOR
A union definition has the same
format as a structure definition. The
union definition
union number { int x; double y; };
UNION
DECLARATIONS indicates that number is a union
type with members int x and double
y. The union definition is normally
placed in a header and included in
all source files that use the union
type.
OPERATIONS THAT CAN BE PERFORMED ON UNIONS
{ if (a == b)
{ puts("equal");
} else
{ puts("not equal");
}}
The a==b comparison will AFAIK throw a compile error on any sensible C compiler,
because the C standard doesn't allow for built-in structure comparison. Workarounds using
memcmp are of course a bad idea due to alignment, packing, bitfields etc., so we end up
writing element by element comparison functions.
ARRAYS OF
STRUCTUR
ES
All the best