0% found this document useful (0 votes)
21 views20 pages

04 Structures

Uploaded by

Destiny
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views20 pages

04 Structures

Uploaded by

Destiny
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Structures

CEN116 Algorithms and Programming II


Introduction
• Structures—collections of related variables under one name
• known as aggregates in the C standard
• may contain many variables of different types
• typedefs—create aliases for previously defined data types
• unions—similar to structures, but members share the same storage
Structure Definitions
• Structures are derived data types—they’re constructed using objects of other
types
• struct introduces a structure definition
• struct card {
const char *face;
const char *suit;
};
• card is the structure tag – used with struct to declare variables of the
structure type
• Variables declared within the braces are the structure’s members
Structure Definitions
• Each structure definition ends with a semicolon
• struct to represent an employee
• struct employee {
char firstName[20];
char lastName[20];
int age;
double hourlySalary;
};
Self-Referential Structures
• A struct may not contain a variable of its own struct type, but it may contain a
pointer to that struct type
• struct employee {
char firstName[20];
char lastName[20];
unsigned int age;
double hourlySalary;
struct employee *managerPtr; // pointer
};
• This is a self-referential structure
• Commonly used to build linked data structures
Defining Variables of Structure Types
• A structure definition does not reserve any space in memory
• Creates a new data type you can use to define variables
• struct card myCard;
struct card deck[52];
struct card *cardPtr;
• Variables of a given structure type may also be defined by placing a comma-
separated list of variable names between the closing brace and terminating
semicolon
• struct card {
const char *face;
const char *suit;
} myCard, deck[52], *cardPtr;
Structure Tag Names
• Structure tag name is optional
• If a structure definition does not specify a tag name, you must define
any variables of the type, as shown in the preceding code snippet
Operations That Can Be Performed on
Structures
• Assigning one struct variable to another of the same type
• for a pointer member, this copies only the address stored in the pointer
• Taking the address (&) of a struct variable
• Accessing a struct variable’s members
• Using the sizeof operator to determine a struct variable’s size
• Zero initializing a struct variable in its definition, as in
• struct card myCard = {};
Operations That Can Be Performed on
Structures
• Comparing Structure Objects Is Not Allowed
• Structures may not be compared because structure members may not be
stored in consecutive bytes of memory
• Sometimes there are “holes”
• Machine-dependent
• Consider
• struct example {
char c;
int i;
} sample1, sample2;
• A computer with four-byte words might require that each member be aligned
on a word boundary
Operations That Can Be Performed on
Structures

• If so, each struct example variable has a three-byte hole


• The hole’s value is unspecified
Initializing Structures
• Can initialize via an initializer list
• struct card myCard = {"Three“, "Hearts"};
• If there are fewer initializers than members, the remaining members are
automatically initialized to 0 or NULL (for pointer members)
• Structure variables defined outside a function definition (i.e., externally) are
initialized to 0 or NULL if they’re not explicitly initialized in the external definition
• You may also assign structure variables to other structure variables of the same
type or assign values to individual structure members
Accessing Structure Members with . and ->
Structure Member Operator (.)
• Accesses a structure member via a structure variable name
• printf("%s", myCard.suit); // displays Hearts
Structure Pointer Operator ->
• Access a structure member via a pointer to the structure
• printf("%s", cardPtr->suit); // displays Hearts
• cardPtr->suit is equivalent to (*cardPtr).suit
• Parentheses are needed here because the structure member operator (.) has
higher precedence than the pointer dereferencing operatör
Spacing Conventions
• Do not put spaces around the -> and . (dot) operators
Using Structures with Functions
• Individual structure members and entire structure objects are passed by value, so
functions cannot modify them in the caller
• To pass a structure by reference, use the structure object’s address
• More efficient than passing structures by value
• Arrays of structure objects are automatically passed by reference
• Passing an Array By Value
• You can use a structure to pass an array by value
• To do so, create a structure with an array member
• Structures are passed by value, so its members are passed by value
typedef
• Enables you to create synonyms (or aliases) for previously defined
types
• Commonly used to create shorter names for struct types
• typedef struct card Card;
• By convention, capitalize the first letter of typedef names to
emphasize that they’re synonyms for other type names
• Use Card to declare variables
• Card deck[52];
• typedef does not create a new type—just an alternate type name
typedef
• Combining typedef with struct Definitions
• Programmers often use typedef to define a structure type, so a
structure tag is not required
• typedef struct {
const char *face;
const char *suit;
} Card;
Unions
• Members share the same memory
• At different times during program execution, some variables may not be
relevant when others are
• So, a union shares the space rather than wasting storage on variables that are
not in use. A union’s members can be of any type
• The number of bytes used to store a union must be at least enough to hold its
largest member
• Can reference only one member—and thus only one type—at a time
• Referencing the currently stored data with a variable of the wrong type is a logic
error
Unions
• Union Portability
• May not port easily among computer systems
• Often depends on the memory alignment requirements for
member types on a given system
union Declarations
• union number {
int x;
double y;
};
• Creates a new type
• Does not reserve any memory until you use the type to create
variables
Allowed unions Operations
• The operations that can be performed on a union are:
• assigning a union to another union of the same type,
• taking a union variable’s address (&),
• accessing union members via the structure member operator (.)
and the structure pointer operator (->) and zero-initializing the
union.
• Two unions may not be compared using operators == and != for the
same reasons that two structures cannot be compared.
References
• C How to Program, Ninth Edition by Deitel & Deitel, Pearson, 2022.

You might also like