Structures, Unions, and T
ypedefs
CS-2303, C-Term 2010 1
Structures, Unions, and Typedefs
CS-2303
System Programming Concepts
(Slides include materials from The C Programming Language, 2nd
edition, by Kernighan and Ritchie and
from C: How to Program, 5th
and 6th
editions, by Deitel and Deitel)
Structures, Unions, and T
ypedefs
CS-2303, C-Term 2010 2
Reading Assignment
• Chapter 6 of Kernighan & Ritchie
Chapter 10 of Deitel & Deitel
Structures, Unions, and T
ypedefs
CS-2303, C-Term 2010 3
Structures and Unions
• The last major language facility in C to be
introduced in this course.
• Essential for building up “interesting” data
structures — e.g.,
• Data structures of multiple values of different kinds
• Data structures of indeterminate size
Structures, Unions, and T
ypedefs
CS-2303, C-Term 2010 4
Definition — Structure
• A collection of one or more variables,
typically of different types, grouped
together under a single name for convenient
handling
• Known as struct in C and C++
Like a class in Java
but with no methods
In C++, a struct is a
class with no methods
Structures, Unions, and T
ypedefs
CS-2303, C-Term 2010 5
struct
• Defines a new type
• I.e., a new kind of data type that compiler regards as
a unit
• E.g.,
struct motor {
float volts; //voltage of the motor
float amps; //amperage of the motor
int phases; //# of phases of the motor
float rpm; //rotational speed of motor
}; //struct motor
Structures, Unions, and T
ypedefs
CS-2303, C-Term 2010 6
struct
• Defines a new type
• E.g.,
struct motor {
float volts;
float amps;
int phases;
float rpm;
}; //struct motor
Name of the type
Note:– name of type is optional if
you are just declaring a single
struct (middle p. 128 of K&R)
Structures, Unions, and T
ypedefs
CS-2303, C-Term 2010 7
struct
• Defines a new type
• E.g.,
struct motor {
float volts;
float amps;
int phases;
float rpm;
}; //struct motor
Members of the
struct
A member of a struct is analogous
to a field of a class in Java
Structures, Unions, and T
ypedefs
CS-2303, C-Term 2010 8
Declaring struct variables
struct motor p, q, r;
• Declares and sets aside storage for three variables –
p, q, and r – each of type struct motor
struct motor M[25];
• Declares a 25-element array of struct motor;
allocates 25 units of storage, each one big enough to
hold the data of one motor
struct motor *m;
• Declares a pointer to an object of type struct
motor
Structures, Unions, and T
ypedefs
CS-2303, C-Term 2010 9
Accessing Members of a struct
• Let
struct motor p;
struct motor q[10];
• Then
p.volts — is the voltage
p.amps — is the amperage
p.phases — is the number of phases
p.rpm — is the rotational speed
q[i].volts — is the voltage of the ith motor
q[i].rpm — is the speed of the ith motor
Like Java!
Structures, Unions, and T
ypedefs
CS-2303, C-Term 2010 10
Accessing Members of a struct (continued)
• Let
struct motor *p;
• Then
(*p).volts — is the voltage of the motor pointed
to by p
(*p).phases — is the number of phases of the
motor pointed to by p
Why the parentheses?
Structures, Unions, and T
ypedefs
CS-2303, C-Term 2010 11
Accessing Members of a struct (continued)
• Let
struct motor *p;
• Then
(*p).volts — is the voltage of the motor pointed
to by p
(*p).phases — is the number of phases of the
motor pointed to by p
Because '.' operator
has higher precedence
than unary '*'
Structures, Unions, and T
ypedefs
CS-2303, C-Term 2010 12
Accessing Members of a struct (continued)
• Let
struct motor *p;
• Then
(*p).volts — is the voltage of the motor pointed
to by p
(*p).phases — is the number of phases of the
motor pointed to by p
Reason:– you really want the expression
m.volts * m.amps
to mean what you think it should mean!
Structures, Unions, and T
ypedefs
CS-2303, C-Term 2010 13
Accessing Members of a struct (continued)
• The (*p).member notation is a nuisance
• Clumsy to type; need to match ( )
• Too many keystrokes
• This construct is so widely used that a
special notation was invented, i.e.,
– p->member, where p is a pointer to the
structure
• Ubiquitous in C and C++
Structures, Unions, and T
ypedefs
CS-2303, C-Term 2010 14
Previous Example Becomes …
• Let
struct motor *p;
• Then
p -> volts — is the voltage of the motor pointed
to by p
p -> phases — is the number of phases of the
motor pointed to by p
Structures, Unions, and T
ypedefs
CS-2303, C-Term 2010 15
Operations on struct
• Copy/assign
struct motor p, q;
p = q;
• Get address
struct motor p;
struct motor *s
s = &p;
• Access members
p.volts;
s -> amps;
Structures, Unions, and T
ypedefs
CS-2303, C-Term 2010 16
Operations on struct (continued)
• Remember:–
– Passing an argument by value is an instance of copying
or assignment
– Passing a return value from a function to the caller is an
instance of copying or assignment
• E.g,:–
struct motor f(struct motor g) {
struct motor h = g;
...;
return h;
}
Structures, Unions, and T
ypedefs
CS-2303, C-Term 2010 17
Assigning to a struct
• K & R say (p. 131)
– “If a large structure is to be passed to a function, it is
generally more efficient to pass a pointer than to copy
the whole structure”
• I disagree:–
– Copying is very fast on modern computers
– Creating an object with malloc() and assigning a
pointer is not as fast
– Esp. if you want the object passed or returned by value
– In real life situations, it is a judgment call
Structures, Unions, and T
ypedefs
CS-2303, C-Term 2010 18
Initialization of a struct
• Let struct motor {
float volts;
float amps;
int phases;
float rpm;
}; //struct motor
• Then
struct motor m = {208, 20, 3,
1800};
initializes the struct
• See also p. 133 of K&R for initializing arrays of
structs
C99 introduces a new
way of initializing a
struct – truly ugly!
Structures, Unions, and T
ypedefs
CS-2303, C-Term 2010 19
Why structs?
• Open-ended data structures
– E.g., structures that may grow during
processing
– Avoids the need for realloc() and a lot of
copying
• Self-referential data structures
– Lists, trees, etc.
Structures, Unions, and T
ypedefs
CS-2303, C-Term 2010 20
Example
struct item {
char *s;
struct item *next;
}
• I.e., an item can point to another item
• … which can point to another item
• … which can point to yet another item
• … etc.
Thereby forming a list of items
Yes! This is legal!
Structures, Unions, and T
ypedefs
CS-2303, C-Term 2010 21
A note about structs and pointers
• The following is legal:–
/* in a .c or .h file */
struct item;
struct item *p, *q;
… /* In another file */
struct item {
int member1;
float member2;
struct item *member3;
};
Called an opaque type!
Program can use pointers to items
but cannot see into items.
Cannot define any items, cannot
malloc any items, etc.
Implementer of item can change
the definition without forcing
users of pointers to change their
code!
Structures, Unions, and T
ypedefs
CS-2303, C-Term 2010 22
Another note about structs
• The following is not legal:–
struct motor {
float volts;
float amps;
float rpm;
unsigned int phases;
}; //struct motor
motor m;
motor *p;
You must write
struct motor m;
struct motor *p;
Structures, Unions, and T
ypedefs
CS-2303, C-Term 2010 23
Typedef
• Definition:– a typedef is a way of
renaming a type
– See §6.7
• E.g.,
typedef struct motor Motor;
Motor m, n;
Motor *p, r[25];
Motor function(const Motor m; …);
E.g., typedef, lets you
leave out the word “struct”
Structures, Unions, and T
ypedefs
CS-2303, C-Term 2010 24
typedef (continued)
• typedef may be used to rename any type
– Convenience in naming
– Clarifies purpose of the type
– Cleaner, more readable code
– Portability across platforms
• E.g.,
– typedef char *String;
• E.g.,
– typedef int size_t;
– typedef long int32;
– typedef long long int64;
Structures, Unions, and T
ypedefs
CS-2303, C-Term 2010 25
typedef (continued)
• typedef may be used to rename any type
– Convenience in naming
– Clarifies purpose of the type
– Cleaner, more readable code
– Portability across platforms
• E.g.,
– typedef char *String;
• E.g.,
– typedef int size_t;
– typedef long int32;
– typedef long long int64;
These three may change from
platform to platform
Defined once in a .h file!
Very common in C and C++
Esp. for portable code!
Structures, Unions, and T
ypedefs
CS-2303, C-Term 2010 26
Revisit note about structs and pointers
• The following is legal:–
/* in a .c or .h file */
typedef struct _item Item;
Item *p, *q;
… /* In another file */
struct _item {
char *info;
Item *nextItem;
};
Structures, Unions, and T
ypedefs
CS-2303, C-Term 2010 27
Questions about structs and pointers?
Structures, Unions, and T
ypedefs
CS-2303, C-Term 2010 28
Unions
• A union is like a struct, but only one of its
members is stored, not all
• I.e., a single variable may hold different types at different
times
• Storage is enough to hold largest member
• Members are overlaid on top of each other
• E.g.,
union {
int ival;
float fval;
char *sval;
} u;
Structures, Unions, and T
ypedefs
CS-2303, C-Term 2010 29
Unions (continued)
• It is programmer’s responsibility to keep track of
which type is stored in a union at any given time!
• E.g., (p. 148)
struct taggedItem {
enum {iType, fType, cType} tag;
union {
int ival;
float fval;
char *sval;
} u;
};
Structures, Unions, and T
ypedefs
CS-2303, C-Term 2010 30
Unions (continued)
• It is programmer’s responsibility to keep track of
which type is stored in a union at any given time!
• E.g., (p. 148)
struct taggedItem {
enum {iType, fType, cType} tag;
union {
int ival;
float fval;
char *sval;
} u;
};
Members of struct are:–
enum tag;
union u;
Value of tag says which
member of u to use
Structures, Unions, and T
ypedefs
CS-2303, C-Term 2010 31
Unions (continued)
• unions are used much less frequently than
structs — mostly
• in the inner details of operating system
• in device drivers
• in embedded systems where you have to access
registers defined by the hardware
Structures, Unions, and T
ypedefs
CS-2303, C-Term 2010 32
Questions?

More Related Content

PPTX
DOC
Structures unions
PPT
C Structures & Unions
PPTX
C Programming: Structure and Union
PPTX
vkvkhkdflaksjdlfjalkjfaljklajskldjaklsjdklajsdkljaklsjdklajskdljaklsdjklaj
PPT
structures and unions in 'C'
PDF
Chapter 13.1.9
PPTX
ECE2102-Week13 - 14-Strhhhhhhhjjjucts.pptx
Structures unions
C Structures & Unions
C Programming: Structure and Union
vkvkhkdflaksjdlfjalkjfaljklajskldjaklsjdklajsdkljaklsjdklajskdljaklsdjklaj
structures and unions in 'C'
Chapter 13.1.9
ECE2102-Week13 - 14-Strhhhhhhhjjjucts.pptx

Similar to Week2_StructuresEtcgghjjvfyiigggbjkyt.ppt (20)

PDF
Unit 4 qba
PPTX
introduction-of-struct-union in deatil.pptx
PPT
SPC Unit 5
PDF
slideset 7 structure and union (1).pdf
PDF
Lk module4 structures
PPTX
Programming in C session 3
PPT
structure and union from C programming Language
PPT
structure and union from c programming language.ppt
PDF
C- language Lecture 7
PPTX
Structures
DOCX
C programming structures & union
DOCX
Structure and Typedef
PPTX
Computer science ( Structures In C ) Ppt
PPTX
structenumtypedefunion.pptx
PDF
Structures, Unions, and Storage Classes in C: Organizing Complex Data and Man...
PPT
Structures and Unions in C-Language with Examples.ppt
PPT
Introduction to structures in c lang.ppt
PPT
structures.ppt
PPTX
Unit-V.pptx
PDF
VIT351 Software Development VI Unit4
Unit 4 qba
introduction-of-struct-union in deatil.pptx
SPC Unit 5
slideset 7 structure and union (1).pdf
Lk module4 structures
Programming in C session 3
structure and union from C programming Language
structure and union from c programming language.ppt
C- language Lecture 7
Structures
C programming structures & union
Structure and Typedef
Computer science ( Structures In C ) Ppt
structenumtypedefunion.pptx
Structures, Unions, and Storage Classes in C: Organizing Complex Data and Man...
Structures and Unions in C-Language with Examples.ppt
Introduction to structures in c lang.ppt
structures.ppt
Unit-V.pptx
VIT351 Software Development VI Unit4
Ad

Recently uploaded (9)

PDF
Kids, Screens & Emotional Development by Meenakshi Khakat
PPTX
Social Media People PowerPoint Templates.pptx
PDF
Date Right Stuff - Invite only, conservative dating app
DOC
NIU毕业证学历认证,阿比林基督大学毕业证留学生学历
DOC
SIUE毕业证学历认证,阿祖萨太平洋大学毕业证学位证书复制
PDF
2025 Guide to Buy Verified Cash App Accounts You Can Trust.pdf
DOC
EIU毕业证学历认证,贝尔维尤学院毕业证国外毕业证
PDF
Best 4 Sites for Buy Verified Cash App Accounts – BTC Only.pdf
PPTX
Introduction to Packet Tracer Course Overview - Aug 21 (1).pptx
Kids, Screens & Emotional Development by Meenakshi Khakat
Social Media People PowerPoint Templates.pptx
Date Right Stuff - Invite only, conservative dating app
NIU毕业证学历认证,阿比林基督大学毕业证留学生学历
SIUE毕业证学历认证,阿祖萨太平洋大学毕业证学位证书复制
2025 Guide to Buy Verified Cash App Accounts You Can Trust.pdf
EIU毕业证学历认证,贝尔维尤学院毕业证国外毕业证
Best 4 Sites for Buy Verified Cash App Accounts – BTC Only.pdf
Introduction to Packet Tracer Course Overview - Aug 21 (1).pptx
Ad

Week2_StructuresEtcgghjjvfyiigggbjkyt.ppt

  • 1. Structures, Unions, and T ypedefs CS-2303, C-Term 2010 1 Structures, Unions, and Typedefs CS-2303 System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition, by Kernighan and Ritchie and from C: How to Program, 5th and 6th editions, by Deitel and Deitel)
  • 2. Structures, Unions, and T ypedefs CS-2303, C-Term 2010 2 Reading Assignment • Chapter 6 of Kernighan & Ritchie Chapter 10 of Deitel & Deitel
  • 3. Structures, Unions, and T ypedefs CS-2303, C-Term 2010 3 Structures and Unions • The last major language facility in C to be introduced in this course. • Essential for building up “interesting” data structures — e.g., • Data structures of multiple values of different kinds • Data structures of indeterminate size
  • 4. Structures, Unions, and T ypedefs CS-2303, C-Term 2010 4 Definition — Structure • A collection of one or more variables, typically of different types, grouped together under a single name for convenient handling • Known as struct in C and C++ Like a class in Java but with no methods In C++, a struct is a class with no methods
  • 5. Structures, Unions, and T ypedefs CS-2303, C-Term 2010 5 struct • Defines a new type • I.e., a new kind of data type that compiler regards as a unit • E.g., struct motor { float volts; //voltage of the motor float amps; //amperage of the motor int phases; //# of phases of the motor float rpm; //rotational speed of motor }; //struct motor
  • 6. Structures, Unions, and T ypedefs CS-2303, C-Term 2010 6 struct • Defines a new type • E.g., struct motor { float volts; float amps; int phases; float rpm; }; //struct motor Name of the type Note:– name of type is optional if you are just declaring a single struct (middle p. 128 of K&R)
  • 7. Structures, Unions, and T ypedefs CS-2303, C-Term 2010 7 struct • Defines a new type • E.g., struct motor { float volts; float amps; int phases; float rpm; }; //struct motor Members of the struct A member of a struct is analogous to a field of a class in Java
  • 8. Structures, Unions, and T ypedefs CS-2303, C-Term 2010 8 Declaring struct variables struct motor p, q, r; • Declares and sets aside storage for three variables – p, q, and r – each of type struct motor struct motor M[25]; • Declares a 25-element array of struct motor; allocates 25 units of storage, each one big enough to hold the data of one motor struct motor *m; • Declares a pointer to an object of type struct motor
  • 9. Structures, Unions, and T ypedefs CS-2303, C-Term 2010 9 Accessing Members of a struct • Let struct motor p; struct motor q[10]; • Then p.volts — is the voltage p.amps — is the amperage p.phases — is the number of phases p.rpm — is the rotational speed q[i].volts — is the voltage of the ith motor q[i].rpm — is the speed of the ith motor Like Java!
  • 10. Structures, Unions, and T ypedefs CS-2303, C-Term 2010 10 Accessing Members of a struct (continued) • Let struct motor *p; • Then (*p).volts — is the voltage of the motor pointed to by p (*p).phases — is the number of phases of the motor pointed to by p Why the parentheses?
  • 11. Structures, Unions, and T ypedefs CS-2303, C-Term 2010 11 Accessing Members of a struct (continued) • Let struct motor *p; • Then (*p).volts — is the voltage of the motor pointed to by p (*p).phases — is the number of phases of the motor pointed to by p Because '.' operator has higher precedence than unary '*'
  • 12. Structures, Unions, and T ypedefs CS-2303, C-Term 2010 12 Accessing Members of a struct (continued) • Let struct motor *p; • Then (*p).volts — is the voltage of the motor pointed to by p (*p).phases — is the number of phases of the motor pointed to by p Reason:– you really want the expression m.volts * m.amps to mean what you think it should mean!
  • 13. Structures, Unions, and T ypedefs CS-2303, C-Term 2010 13 Accessing Members of a struct (continued) • The (*p).member notation is a nuisance • Clumsy to type; need to match ( ) • Too many keystrokes • This construct is so widely used that a special notation was invented, i.e., – p->member, where p is a pointer to the structure • Ubiquitous in C and C++
  • 14. Structures, Unions, and T ypedefs CS-2303, C-Term 2010 14 Previous Example Becomes … • Let struct motor *p; • Then p -> volts — is the voltage of the motor pointed to by p p -> phases — is the number of phases of the motor pointed to by p
  • 15. Structures, Unions, and T ypedefs CS-2303, C-Term 2010 15 Operations on struct • Copy/assign struct motor p, q; p = q; • Get address struct motor p; struct motor *s s = &p; • Access members p.volts; s -> amps;
  • 16. Structures, Unions, and T ypedefs CS-2303, C-Term 2010 16 Operations on struct (continued) • Remember:– – Passing an argument by value is an instance of copying or assignment – Passing a return value from a function to the caller is an instance of copying or assignment • E.g,:– struct motor f(struct motor g) { struct motor h = g; ...; return h; }
  • 17. Structures, Unions, and T ypedefs CS-2303, C-Term 2010 17 Assigning to a struct • K & R say (p. 131) – “If a large structure is to be passed to a function, it is generally more efficient to pass a pointer than to copy the whole structure” • I disagree:– – Copying is very fast on modern computers – Creating an object with malloc() and assigning a pointer is not as fast – Esp. if you want the object passed or returned by value – In real life situations, it is a judgment call
  • 18. Structures, Unions, and T ypedefs CS-2303, C-Term 2010 18 Initialization of a struct • Let struct motor { float volts; float amps; int phases; float rpm; }; //struct motor • Then struct motor m = {208, 20, 3, 1800}; initializes the struct • See also p. 133 of K&R for initializing arrays of structs C99 introduces a new way of initializing a struct – truly ugly!
  • 19. Structures, Unions, and T ypedefs CS-2303, C-Term 2010 19 Why structs? • Open-ended data structures – E.g., structures that may grow during processing – Avoids the need for realloc() and a lot of copying • Self-referential data structures – Lists, trees, etc.
  • 20. Structures, Unions, and T ypedefs CS-2303, C-Term 2010 20 Example struct item { char *s; struct item *next; } • I.e., an item can point to another item • … which can point to another item • … which can point to yet another item • … etc. Thereby forming a list of items Yes! This is legal!
  • 21. Structures, Unions, and T ypedefs CS-2303, C-Term 2010 21 A note about structs and pointers • The following is legal:– /* in a .c or .h file */ struct item; struct item *p, *q; … /* In another file */ struct item { int member1; float member2; struct item *member3; }; Called an opaque type! Program can use pointers to items but cannot see into items. Cannot define any items, cannot malloc any items, etc. Implementer of item can change the definition without forcing users of pointers to change their code!
  • 22. Structures, Unions, and T ypedefs CS-2303, C-Term 2010 22 Another note about structs • The following is not legal:– struct motor { float volts; float amps; float rpm; unsigned int phases; }; //struct motor motor m; motor *p; You must write struct motor m; struct motor *p;
  • 23. Structures, Unions, and T ypedefs CS-2303, C-Term 2010 23 Typedef • Definition:– a typedef is a way of renaming a type – See §6.7 • E.g., typedef struct motor Motor; Motor m, n; Motor *p, r[25]; Motor function(const Motor m; …); E.g., typedef, lets you leave out the word “struct”
  • 24. Structures, Unions, and T ypedefs CS-2303, C-Term 2010 24 typedef (continued) • typedef may be used to rename any type – Convenience in naming – Clarifies purpose of the type – Cleaner, more readable code – Portability across platforms • E.g., – typedef char *String; • E.g., – typedef int size_t; – typedef long int32; – typedef long long int64;
  • 25. Structures, Unions, and T ypedefs CS-2303, C-Term 2010 25 typedef (continued) • typedef may be used to rename any type – Convenience in naming – Clarifies purpose of the type – Cleaner, more readable code – Portability across platforms • E.g., – typedef char *String; • E.g., – typedef int size_t; – typedef long int32; – typedef long long int64; These three may change from platform to platform Defined once in a .h file! Very common in C and C++ Esp. for portable code!
  • 26. Structures, Unions, and T ypedefs CS-2303, C-Term 2010 26 Revisit note about structs and pointers • The following is legal:– /* in a .c or .h file */ typedef struct _item Item; Item *p, *q; … /* In another file */ struct _item { char *info; Item *nextItem; };
  • 27. Structures, Unions, and T ypedefs CS-2303, C-Term 2010 27 Questions about structs and pointers?
  • 28. Structures, Unions, and T ypedefs CS-2303, C-Term 2010 28 Unions • A union is like a struct, but only one of its members is stored, not all • I.e., a single variable may hold different types at different times • Storage is enough to hold largest member • Members are overlaid on top of each other • E.g., union { int ival; float fval; char *sval; } u;
  • 29. Structures, Unions, and T ypedefs CS-2303, C-Term 2010 29 Unions (continued) • It is programmer’s responsibility to keep track of which type is stored in a union at any given time! • E.g., (p. 148) struct taggedItem { enum {iType, fType, cType} tag; union { int ival; float fval; char *sval; } u; };
  • 30. Structures, Unions, and T ypedefs CS-2303, C-Term 2010 30 Unions (continued) • It is programmer’s responsibility to keep track of which type is stored in a union at any given time! • E.g., (p. 148) struct taggedItem { enum {iType, fType, cType} tag; union { int ival; float fval; char *sval; } u; }; Members of struct are:– enum tag; union u; Value of tag says which member of u to use
  • 31. Structures, Unions, and T ypedefs CS-2303, C-Term 2010 31 Unions (continued) • unions are used much less frequently than structs — mostly • in the inner details of operating system • in device drivers • in embedded systems where you have to access registers defined by the hardware
  • 32. Structures, Unions, and T ypedefs CS-2303, C-Term 2010 32 Questions?