SlideShare a Scribd company logo
1 of 21
Structures and Unions in C
Alan L. Cox
alc@rice.edu
Cox / Fagan Structures and Unions 2
Administrivia
Assignment 1 is due tonight
Textbook
 Lectures begin covering material that is also
covered by the textbook on 1/30
 Assignment 3 (assigned 2/1) requires use of the
textbook
Objectives
Be able to use compound data structures in
programs
Be able to pass compound data structures as
function arguments, either by value or by
reference
Be able to do simple bit-vector manipulations
Cox / Fagan Structures and Unions 3
Cox / Fagan Structures and Unions 4
Structures
Compound data:
A date is
 an int month and
 an int day and
 an int year
Unlike Java, C doesn’t
automatically define functions for
initializing and printing …
struct ADate {
int month;
int day;
int year;
};
struct ADate date;
date.month = 1;
date.day = 18;
date.year = 2018;
Cox / Fagan Structures and Unions 5
Structure Representation & Size
sizeof(struct …) =
sum of sizeof(field)
+ alignment padding
Processor- and compiler-specific
6261 EF BE AD DE
c1 c2 ipadding
struct CharCharInt {
char c1;
char c2;
int i;
} foo;
foo.c1 = ’a’;
foo.c2 = ’b’;
foo.i = 0xDEADBEEF;
x86 uses “little-endian” representation
Cox / Fagan Structures and Unions 6
Typedef
Mechanism for creating new type names
 New names are an alias for some other type
 May improve clarity and/or portability of the
program
typedef long int64_t;
typedef struct ADate {
int month;
int day;
int year;
} Date;
int64_t i = 100000000000;
Date d = { 1, 18, 2018 };
Overload existing type
names for clarity and
portability
Simplify complex type
names
Cox / Fagan Structures and Unions 7
Constants
Allow consistent use of the same constant
throughout the program
 Improves clarity of the program
 Reduces likelihood of simple errors
 Easier to update constants in the program
int array[10];
for (i=0; i<10; i++) {
…
}
#define SIZE 10
int array[SIZE];
for (i=0; i<SIZE; i++) {
…
}
Preprocessor directive
Constant names are
capitalized by convention
Define once,
use throughout
the program
Cox / Fagan Structures and Unions 8
Arrays of Structures
Date birthdays[NFRIENDS];
bool
check_birthday(Date today)
{
int i;
for (i = 0; i < NFRIENDS; i++) {
if ((today.month == birthdays[i].month) &&
(today.day == birthdays[i].day))
return (true);
return (false);
}
ConstantArray declaration
Array index, then
structure field
Cox / Fagan Structures and Unions 9
Pointers to Structures
Date
create_date1(int month,
int day,
int year)
{
Date d;
d.month = month;
d.day = day;
d.year = year;
return (d);
}
void
create_date2(Date *d,
int month,
int day,
int year)
{
d->month = month;
d->day = day;
d->year = year;
}
Copies date
Pass-by-reference
Date today;
today = create_date1(1, 18, 2018);
create_date2(&today, 1, 18, 2018);
Cox / Fagan Structures and Unions 10
Pointers to Structures (cont.)
void
create_date2(Date *d,
int month,
int day,
int year)
{
d->month = month;
d->day = day;
d->year = year;
}
void
fun_with_dates(void)
{
Date today;
create_date2(&today, 1, 18, 2018);
}
today.month:
today.day:
today.year:
0x1000
0x1004
0x1008
month: 1
day: 18
year: 2018
0x30A0
0x30A4
0x30A8
d: 0x10000x3098
1
18
2018
Cox / Fagan Structures and Unions 11
Pointers to Structures (cont.)
Date *
create_date3(int month,
int day,
int year)
{
Date *d;
d->month = month;
d->day = day;
d->year = year;
return (d);
}
What is d pointing to?!?!
(more on this later)
Cox Structures and Unions 12
Abstraction in C
struct widget;
struct widget *widget_create(void);
int widget_op(struct widget *widget, int operand);
void widget_destroy(struct widget *widget);
From the #include file widget.h:
From the file widget.c:
#include “widget.h”
struct widget {
int x;
…
};
Definition is hidden!
Cox / Fagan Structures and Unions 12
Cox / Fagan Structures and Unions 13
Collections of Bools (Bit Vectors)
Byte, word, ... can represent many Booleans
One per bit, e.g., 00100101 = false, false, true, ..., true
Bit-wise operations:
Bit-wise AND: 00100101 & 10111100 == 00100100
Bit-wise OR: 00100101 | 10111100 == 10111101
Bit-wise NOT: ~ 00100101 == 11011010
Bit-wise XOR: 00100101 ^ 10111100 == 10011001
Cox / Fagan Structures and Unions 14
Operations on Bit Vectors
const unsigned int low_three_bits_mask = 0x7;
unsigned int bit_vec = 0x15;
0…00 0111
0…01 0101
Always use C’s unsigned types for bit vectors
A mask indicates which bit positions we are interested in
0…00 0101 == 0…01 0101 & 0…00 0111
important_bits = bit_vec & low_three_bits_mask;
Selecting bits:
Result = ?
Cox / Fagan Structures and Unions 15
Operations on Bit Vectors
const unsigned int low_three_bits_mask = 0x7;
unsigned int bit_vec = 0x15;
0…00 0111
0…01 0101
bit_vec |= low_three_bits_mask;
Setting bits:
Result = ?
0…01 0111 == 0…01 0101 | 0…00 0111
Cox / Fagan Structures and Unions 16
Operations on Bit Vectors
const unsigned int low_three_bits_mask = 0x7;
unsigned int bit_vec = 0x15;
0…00 0111
0…01 0101
bit_vec &= ~low_three_bits_mask;
Clearing bits:
Result = ?
0…01 0000 == 0…01 0101 & ~0…00 0111
Cox / Fagan Structures and Unions 17
Bit-field Structures
Special syntax packs
structure values more
tightly
Similar to bit vectors, but
arguably easier to read
 Nonetheless, bit vectors
are more commonly
used.
Padded to be an integral
number of words
 Placement is compiler-
specific.
1 1 0 1 1 0 … …
f1 f2 f3
struct Flags {
int f1:3;
unsigned int f2:1;
unsigned int f3:2;
} my_flags;
my_flags.f1 = -2;
my_flags.f2 = 1;
my_flags.f3 = 2;
Cox / Fagan Structures and Unions 18
Unions
Choices:
An element is
 an int i or
 a char c
sizeof(union …) =
maximum of sizeof(field)
EF BE AD DE
c
i
padding
union AnElt {
int i;
char c;
} elt1, elt2;
elt1.i = 4;
elt2.c = ’a’;
elt2.i = 0xDEADBEEF;
Cox / Fagan Structures and Unions 19
Unions
A union value doesn’t “know” which case it
contains
union AnElt {
int i;
char c;
} elt1, elt2;
elt1.i = 4;
elt2.c = ’a’;
elt2.i = 0xDEADBEEF;
if (elt1 currently has a char) …
How should your program keep track
whether elt1, elt2 hold an int or
a char?
?
?
Basic answer: Another variable
holds that info
Cox / Fagan Structures and Unions 20
Tagged Unions
Tag every value with its case
I.e., pair the type info together with the union
Implicit in Java, Scheme, ML, …
Enum must be external to struct,
so constants are globally visible.
Struct field must be named.
enum Union_Tag { IS_INT, IS_CHAR };
struct TaggedUnion {
enum Union_Tag tag;
union {
int i;
char c;
} data;
};
Cox / Fagan Structures and Unions 21
Next Time
Memory Allocation

More Related Content

What's hot

one of the rules cited in class for making e-mail more effective Experience T...
one of the rules cited in class for making e-mail more effective Experience T...one of the rules cited in class for making e-mail more effective Experience T...
one of the rules cited in class for making e-mail more effective Experience T...pinck3125
 
Lecture 2 - Classes, Fields, Parameters, Methods and Constructors
Lecture 2 - Classes, Fields, Parameters, Methods and ConstructorsLecture 2 - Classes, Fields, Parameters, Methods and Constructors
Lecture 2 - Classes, Fields, Parameters, Methods and ConstructorsSyed Afaq Shah MACS CP
 
Os sample mid exam
Os sample mid examOs sample mid exam
Os sample mid examMesfin123
 
e computer notes - Reference variables
e computer notes - Reference variablese computer notes - Reference variables
e computer notes - Reference variablesecomputernotes
 
GSP 125 Final Exam Guide
GSP 125 Final Exam GuideGSP 125 Final Exam Guide
GSP 125 Final Exam Guidecritter13
 
GSP 125 Final Exam Guide
GSP 125 Final Exam GuideGSP 125 Final Exam Guide
GSP 125 Final Exam Guidemonsterr20
 
Java Tutorial: Part 4 - Data and Calculations
Java Tutorial: Part 4 - Data and CalculationsJava Tutorial: Part 4 - Data and Calculations
Java Tutorial: Part 4 - Data and CalculationsSvetlin Nakov
 
Dervy bis 155 week 2 quiz new
Dervy   bis 155 week 2 quiz newDervy   bis 155 week 2 quiz new
Dervy bis 155 week 2 quiz newkxipvscsk02
 
Devry bis 155 week 2 quiz new
Devry bis 155 week 2 quiz newDevry bis 155 week 2 quiz new
Devry bis 155 week 2 quiz newuopassignment
 
Intake 38 data access 4
Intake 38 data access 4Intake 38 data access 4
Intake 38 data access 4Mahmoud Ouf
 

What's hot (19)

one of the rules cited in class for making e-mail more effective Experience T...
one of the rules cited in class for making e-mail more effective Experience T...one of the rules cited in class for making e-mail more effective Experience T...
one of the rules cited in class for making e-mail more effective Experience T...
 
Lecture 2 - Classes, Fields, Parameters, Methods and Constructors
Lecture 2 - Classes, Fields, Parameters, Methods and ConstructorsLecture 2 - Classes, Fields, Parameters, Methods and Constructors
Lecture 2 - Classes, Fields, Parameters, Methods and Constructors
 
Os sample mid exam
Os sample mid examOs sample mid exam
Os sample mid exam
 
CBSE Sample Paper IP
CBSE Sample Paper IPCBSE Sample Paper IP
CBSE Sample Paper IP
 
e computer notes - Reference variables
e computer notes - Reference variablese computer notes - Reference variables
e computer notes - Reference variables
 
Lesson 5 link list
Lesson 5  link listLesson 5  link list
Lesson 5 link list
 
Pointers in C language
Pointers  in  C languagePointers  in  C language
Pointers in C language
 
Input output
Input outputInput output
Input output
 
Structure in C
Structure in CStructure in C
Structure in C
 
User Defined Functions in C Language
User Defined Functions   in  C LanguageUser Defined Functions   in  C Language
User Defined Functions in C Language
 
GSP 125 Final Exam Guide
GSP 125 Final Exam GuideGSP 125 Final Exam Guide
GSP 125 Final Exam Guide
 
Gsp 125 final exam guide
Gsp 125 final exam guideGsp 125 final exam guide
Gsp 125 final exam guide
 
GSP 125 Final Exam Guide
GSP 125 Final Exam GuideGSP 125 Final Exam Guide
GSP 125 Final Exam Guide
 
Java Tutorial: Part 4 - Data and Calculations
Java Tutorial: Part 4 - Data and CalculationsJava Tutorial: Part 4 - Data and Calculations
Java Tutorial: Part 4 - Data and Calculations
 
Structures in c++
Structures in c++Structures in c++
Structures in c++
 
Dervy bis 155 week 2 quiz new
Dervy   bis 155 week 2 quiz newDervy   bis 155 week 2 quiz new
Dervy bis 155 week 2 quiz new
 
C Structures And Unions
C  Structures And  UnionsC  Structures And  Unions
C Structures And Unions
 
Devry bis 155 week 2 quiz new
Devry bis 155 week 2 quiz newDevry bis 155 week 2 quiz new
Devry bis 155 week 2 quiz new
 
Intake 38 data access 4
Intake 38 data access 4Intake 38 data access 4
Intake 38 data access 4
 

Similar to 04 struct-union

Structure and Union.ppt
Structure and Union.pptStructure and Union.ppt
Structure and Union.pptSeethaDinesh
 
04-struct-union.ppt
04-struct-union.ppt04-struct-union.ppt
04-struct-union.pptMd Polash
 
Lesson 21. Pattern 13. Data alignment
Lesson 21. Pattern 13. Data alignmentLesson 21. Pattern 13. Data alignment
Lesson 21. Pattern 13. Data alignmentPVS-Studio
 
CLASSES, STRUCTURE,UNION in C++
CLASSES, STRUCTURE,UNION in C++CLASSES, STRUCTURE,UNION in C++
CLASSES, STRUCTURE,UNION in C++Prof Ansari
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And AnswerJagan Mohan Bishoyi
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answerlavparmar007
 
C programming session 09
C programming session 09C programming session 09
C programming session 09Dushmanta Nath
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answersAkash Gawali
 
C programming session 13
C programming session 13C programming session 13
C programming session 13Vivek Singh
 
C questions
C questionsC questions
C questionsparm112
 
Maxbox starter19
Maxbox starter19Maxbox starter19
Maxbox starter19Max Kleiner
 
cprogramming Structures.pptx
cprogramming Structures.pptxcprogramming Structures.pptx
cprogramming Structures.pptxLECO9
 
cprogramming Structures.pptx
cprogramming Structures.pptxcprogramming Structures.pptx
cprogramming Structures.pptxSKUP1
 

Similar to 04 struct-union (20)

Structure and Union.ppt
Structure and Union.pptStructure and Union.ppt
Structure and Union.ppt
 
04-struct-union.ppt
04-struct-union.ppt04-struct-union.ppt
04-struct-union.ppt
 
04-struct-union.ppt
04-struct-union.ppt04-struct-union.ppt
04-struct-union.ppt
 
Chapter 8 Structure Part 2 (1).pptx
Chapter 8 Structure Part 2 (1).pptxChapter 8 Structure Part 2 (1).pptx
Chapter 8 Structure Part 2 (1).pptx
 
Lesson 21. Pattern 13. Data alignment
Lesson 21. Pattern 13. Data alignmentLesson 21. Pattern 13. Data alignment
Lesson 21. Pattern 13. Data alignment
 
CLASSES, STRUCTURE,UNION in C++
CLASSES, STRUCTURE,UNION in C++CLASSES, STRUCTURE,UNION in C++
CLASSES, STRUCTURE,UNION in C++
 
Op ps
Op psOp ps
Op ps
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And Answer
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answer
 
Unit 4 qba
Unit 4 qbaUnit 4 qba
Unit 4 qba
 
C programming session 09
C programming session 09C programming session 09
C programming session 09
 
Structures
StructuresStructures
Structures
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers
 
Structures
StructuresStructures
Structures
 
C programming session 13
C programming session 13C programming session 13
C programming session 13
 
C Programming - Refresher - Part IV
C Programming - Refresher - Part IVC Programming - Refresher - Part IV
C Programming - Refresher - Part IV
 
C questions
C questionsC questions
C questions
 
Maxbox starter19
Maxbox starter19Maxbox starter19
Maxbox starter19
 
cprogramming Structures.pptx
cprogramming Structures.pptxcprogramming Structures.pptx
cprogramming Structures.pptx
 
cprogramming Structures.pptx
cprogramming Structures.pptxcprogramming Structures.pptx
cprogramming Structures.pptx
 

Recently uploaded

18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 

Recently uploaded (20)

18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 

04 struct-union

  • 1. Structures and Unions in C Alan L. Cox alc@rice.edu
  • 2. Cox / Fagan Structures and Unions 2 Administrivia Assignment 1 is due tonight Textbook  Lectures begin covering material that is also covered by the textbook on 1/30  Assignment 3 (assigned 2/1) requires use of the textbook
  • 3. Objectives Be able to use compound data structures in programs Be able to pass compound data structures as function arguments, either by value or by reference Be able to do simple bit-vector manipulations Cox / Fagan Structures and Unions 3
  • 4. Cox / Fagan Structures and Unions 4 Structures Compound data: A date is  an int month and  an int day and  an int year Unlike Java, C doesn’t automatically define functions for initializing and printing … struct ADate { int month; int day; int year; }; struct ADate date; date.month = 1; date.day = 18; date.year = 2018;
  • 5. Cox / Fagan Structures and Unions 5 Structure Representation & Size sizeof(struct …) = sum of sizeof(field) + alignment padding Processor- and compiler-specific 6261 EF BE AD DE c1 c2 ipadding struct CharCharInt { char c1; char c2; int i; } foo; foo.c1 = ’a’; foo.c2 = ’b’; foo.i = 0xDEADBEEF; x86 uses “little-endian” representation
  • 6. Cox / Fagan Structures and Unions 6 Typedef Mechanism for creating new type names  New names are an alias for some other type  May improve clarity and/or portability of the program typedef long int64_t; typedef struct ADate { int month; int day; int year; } Date; int64_t i = 100000000000; Date d = { 1, 18, 2018 }; Overload existing type names for clarity and portability Simplify complex type names
  • 7. Cox / Fagan Structures and Unions 7 Constants Allow consistent use of the same constant throughout the program  Improves clarity of the program  Reduces likelihood of simple errors  Easier to update constants in the program int array[10]; for (i=0; i<10; i++) { … } #define SIZE 10 int array[SIZE]; for (i=0; i<SIZE; i++) { … } Preprocessor directive Constant names are capitalized by convention Define once, use throughout the program
  • 8. Cox / Fagan Structures and Unions 8 Arrays of Structures Date birthdays[NFRIENDS]; bool check_birthday(Date today) { int i; for (i = 0; i < NFRIENDS; i++) { if ((today.month == birthdays[i].month) && (today.day == birthdays[i].day)) return (true); return (false); } ConstantArray declaration Array index, then structure field
  • 9. Cox / Fagan Structures and Unions 9 Pointers to Structures Date create_date1(int month, int day, int year) { Date d; d.month = month; d.day = day; d.year = year; return (d); } void create_date2(Date *d, int month, int day, int year) { d->month = month; d->day = day; d->year = year; } Copies date Pass-by-reference Date today; today = create_date1(1, 18, 2018); create_date2(&today, 1, 18, 2018);
  • 10. Cox / Fagan Structures and Unions 10 Pointers to Structures (cont.) void create_date2(Date *d, int month, int day, int year) { d->month = month; d->day = day; d->year = year; } void fun_with_dates(void) { Date today; create_date2(&today, 1, 18, 2018); } today.month: today.day: today.year: 0x1000 0x1004 0x1008 month: 1 day: 18 year: 2018 0x30A0 0x30A4 0x30A8 d: 0x10000x3098 1 18 2018
  • 11. Cox / Fagan Structures and Unions 11 Pointers to Structures (cont.) Date * create_date3(int month, int day, int year) { Date *d; d->month = month; d->day = day; d->year = year; return (d); } What is d pointing to?!?! (more on this later)
  • 12. Cox Structures and Unions 12 Abstraction in C struct widget; struct widget *widget_create(void); int widget_op(struct widget *widget, int operand); void widget_destroy(struct widget *widget); From the #include file widget.h: From the file widget.c: #include “widget.h” struct widget { int x; … }; Definition is hidden! Cox / Fagan Structures and Unions 12
  • 13. Cox / Fagan Structures and Unions 13 Collections of Bools (Bit Vectors) Byte, word, ... can represent many Booleans One per bit, e.g., 00100101 = false, false, true, ..., true Bit-wise operations: Bit-wise AND: 00100101 & 10111100 == 00100100 Bit-wise OR: 00100101 | 10111100 == 10111101 Bit-wise NOT: ~ 00100101 == 11011010 Bit-wise XOR: 00100101 ^ 10111100 == 10011001
  • 14. Cox / Fagan Structures and Unions 14 Operations on Bit Vectors const unsigned int low_three_bits_mask = 0x7; unsigned int bit_vec = 0x15; 0…00 0111 0…01 0101 Always use C’s unsigned types for bit vectors A mask indicates which bit positions we are interested in 0…00 0101 == 0…01 0101 & 0…00 0111 important_bits = bit_vec & low_three_bits_mask; Selecting bits: Result = ?
  • 15. Cox / Fagan Structures and Unions 15 Operations on Bit Vectors const unsigned int low_three_bits_mask = 0x7; unsigned int bit_vec = 0x15; 0…00 0111 0…01 0101 bit_vec |= low_three_bits_mask; Setting bits: Result = ? 0…01 0111 == 0…01 0101 | 0…00 0111
  • 16. Cox / Fagan Structures and Unions 16 Operations on Bit Vectors const unsigned int low_three_bits_mask = 0x7; unsigned int bit_vec = 0x15; 0…00 0111 0…01 0101 bit_vec &= ~low_three_bits_mask; Clearing bits: Result = ? 0…01 0000 == 0…01 0101 & ~0…00 0111
  • 17. Cox / Fagan Structures and Unions 17 Bit-field Structures Special syntax packs structure values more tightly Similar to bit vectors, but arguably easier to read  Nonetheless, bit vectors are more commonly used. Padded to be an integral number of words  Placement is compiler- specific. 1 1 0 1 1 0 … … f1 f2 f3 struct Flags { int f1:3; unsigned int f2:1; unsigned int f3:2; } my_flags; my_flags.f1 = -2; my_flags.f2 = 1; my_flags.f3 = 2;
  • 18. Cox / Fagan Structures and Unions 18 Unions Choices: An element is  an int i or  a char c sizeof(union …) = maximum of sizeof(field) EF BE AD DE c i padding union AnElt { int i; char c; } elt1, elt2; elt1.i = 4; elt2.c = ’a’; elt2.i = 0xDEADBEEF;
  • 19. Cox / Fagan Structures and Unions 19 Unions A union value doesn’t “know” which case it contains union AnElt { int i; char c; } elt1, elt2; elt1.i = 4; elt2.c = ’a’; elt2.i = 0xDEADBEEF; if (elt1 currently has a char) … How should your program keep track whether elt1, elt2 hold an int or a char? ? ? Basic answer: Another variable holds that info
  • 20. Cox / Fagan Structures and Unions 20 Tagged Unions Tag every value with its case I.e., pair the type info together with the union Implicit in Java, Scheme, ML, … Enum must be external to struct, so constants are globally visible. Struct field must be named. enum Union_Tag { IS_INT, IS_CHAR }; struct TaggedUnion { enum Union_Tag tag; union { int i; char c; } data; };
  • 21. Cox / Fagan Structures and Unions 21 Next Time Memory Allocation