SlideShare a Scribd company logo
1 of 20
Structures and Unions in C
Alan L. Cox
alc@rice.edu
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 Structures and Unions 2
Cox Structures and Unions 3
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 = 2;
date.day = 4;
date.year = 2021;
Cox Structures and Unions 4
Structure Representation & Size
sizeof(struct …) =
sum of sizeof(field)
+ alignment padding
Processor- and compiler-specific
62
61 EF BE AD DE
c1 c2 i
padding
struct CharCharInt {
char c1;
char c2;
int i;
} foo;
foo.c1 = ’a’;
foo.c2 = ’b’;
foo.i = 0xDEADBEEF;
x86 uses “little-endian” representation
Cox Structures and Unions 5
Typedef
Mechanism for creating new type names
 New names are an alias for some other type
 May improve the portability and/or clarity of the
program
typedef long int64_t;
typedef struct ADate {
int month;
int day;
int year;
} Date;
int64_t i = 100000000000;
Date d = { 2, 4, 2021 };
Overload existing type
names for portability
Simplify complex type names
Cox Structures and Unions 6
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 Structures and Unions 7
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);
}
Constant
Array declaration
Array index, then
structure field
Cox Structures and Unions 8
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(2, 4, 2021);
create_date2(&today, 2, 4, 2021);
Cox Structures and Unions 9
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, 2, 4, 2021);
}
today.month:
today.day:
today.year:
0x1000
0x1004
0x1008
month: 2
day: 4
year: 2021
0x30A0
0x30A4
0x30A8
d: 0x1000
0x3098
2
4
2021
Cox Structures and Unions 10
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 11
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 Structures and Unions 11
Cox Structures and Unions 12
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 Structures and Unions 13
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 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
bit_vec |= low_three_bits_mask;
Setting bits:
Result = ?
0…01 0111 == 0…01 0101 | 0…00 0111
Cox 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;
Clearing bits:
Result = ?
0…01 0000 == 0…01 0101 & ~0…00 0111
Cox Structures and Unions 16
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 Structures and Unions 17
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 Structures and Unions 18
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 Structures and Unions 19
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 Structures and Unions 20
Next Time
Memory Allocation

More Related Content

Similar to 04-struct-union.ppt

Data structure manual
Data structure manualData structure manual
Data structure manualsameer farooq
 
Resource wrappers in C++
Resource wrappers in C++Resource wrappers in C++
Resource wrappers in C++Ilio Catallo
 
"Optimization of a .NET application- is it simple ! / ?", Yevhen Tatarynov
"Optimization of a .NET application- is it simple ! / ?",  Yevhen Tatarynov"Optimization of a .NET application- is it simple ! / ?",  Yevhen Tatarynov
"Optimization of a .NET application- is it simple ! / ?", Yevhen TatarynovFwdays
 
(1) cpp abstractions user_defined_types
(1) cpp abstractions user_defined_types(1) cpp abstractions user_defined_types
(1) cpp abstractions user_defined_typesNico Ludwig
 
C programming session 13
C programming session 13C programming session 13
C programming session 13Vivek Singh
 
(1) cpp abstractions user_defined_types
(1) cpp abstractions user_defined_types(1) cpp abstractions user_defined_types
(1) cpp abstractions user_defined_typesNico Ludwig
 
Python and PostgreSQL: Let's Work Together! | PyConFr 2018 | Dimitri Fontaine
Python and PostgreSQL: Let's Work Together! | PyConFr 2018 | Dimitri FontainePython and PostgreSQL: Let's Work Together! | PyConFr 2018 | Dimitri Fontaine
Python and PostgreSQL: Let's Work Together! | PyConFr 2018 | Dimitri FontaineCitus Data
 
Visual studio 2008
Visual studio 2008Visual studio 2008
Visual studio 2008Luis Enrique
 
CHAPTER -4-class and structure.pptx
CHAPTER -4-class and structure.pptxCHAPTER -4-class and structure.pptx
CHAPTER -4-class and structure.pptxGebruGetachew2
 
C programming & data structure [arrays & pointers]
C programming & data structure   [arrays & pointers]C programming & data structure   [arrays & pointers]
C programming & data structure [arrays & pointers]MomenMostafa
 
introductory concepts
introductory conceptsintroductory concepts
introductory conceptsWalepak Ubi
 
13 -times_and_dates
13  -times_and_dates13  -times_and_dates
13 -times_and_datesHector Garzo
 
Coding - L30-L31-Array of structures.pptx
Coding - L30-L31-Array of structures.pptxCoding - L30-L31-Array of structures.pptx
Coding - L30-L31-Array of structures.pptxhappycocoman
 
Chapter 1 Basic Concepts
Chapter 1 Basic ConceptsChapter 1 Basic Concepts
Chapter 1 Basic ConceptsHareem Aslam
 
CUDA by Example : Parallel Programming in CUDA C : Notes
CUDA by Example : Parallel Programming in CUDA C : NotesCUDA by Example : Parallel Programming in CUDA C : Notes
CUDA by Example : Parallel Programming in CUDA C : NotesSubhajit Sahu
 
A quick introduction to R
A quick introduction to RA quick introduction to R
A quick introduction to RAngshuman Saha
 

Similar to 04-struct-union.ppt (20)

Structures_Final_KLE (2).pptx
Structures_Final_KLE (2).pptxStructures_Final_KLE (2).pptx
Structures_Final_KLE (2).pptx
 
Data structure manual
Data structure manualData structure manual
Data structure manual
 
Resource wrappers in C++
Resource wrappers in C++Resource wrappers in C++
Resource wrappers in C++
 
Week2a.pptx
Week2a.pptxWeek2a.pptx
Week2a.pptx
 
"Optimization of a .NET application- is it simple ! / ?", Yevhen Tatarynov
"Optimization of a .NET application- is it simple ! / ?",  Yevhen Tatarynov"Optimization of a .NET application- is it simple ! / ?",  Yevhen Tatarynov
"Optimization of a .NET application- is it simple ! / ?", Yevhen Tatarynov
 
(1) cpp abstractions user_defined_types
(1) cpp abstractions user_defined_types(1) cpp abstractions user_defined_types
(1) cpp abstractions user_defined_types
 
C programming session 13
C programming session 13C programming session 13
C programming session 13
 
(1) cpp abstractions user_defined_types
(1) cpp abstractions user_defined_types(1) cpp abstractions user_defined_types
(1) cpp abstractions user_defined_types
 
ELAVARASAN.pdf
ELAVARASAN.pdfELAVARASAN.pdf
ELAVARASAN.pdf
 
Python and PostgreSQL: Let's Work Together! | PyConFr 2018 | Dimitri Fontaine
Python and PostgreSQL: Let's Work Together! | PyConFr 2018 | Dimitri FontainePython and PostgreSQL: Let's Work Together! | PyConFr 2018 | Dimitri Fontaine
Python and PostgreSQL: Let's Work Together! | PyConFr 2018 | Dimitri Fontaine
 
Visual studio 2008
Visual studio 2008Visual studio 2008
Visual studio 2008
 
CHAPTER -4-class and structure.pptx
CHAPTER -4-class and structure.pptxCHAPTER -4-class and structure.pptx
CHAPTER -4-class and structure.pptx
 
C programming & data structure [arrays & pointers]
C programming & data structure   [arrays & pointers]C programming & data structure   [arrays & pointers]
C programming & data structure [arrays & pointers]
 
Structures
StructuresStructures
Structures
 
introductory concepts
introductory conceptsintroductory concepts
introductory concepts
 
13 -times_and_dates
13  -times_and_dates13  -times_and_dates
13 -times_and_dates
 
Coding - L30-L31-Array of structures.pptx
Coding - L30-L31-Array of structures.pptxCoding - L30-L31-Array of structures.pptx
Coding - L30-L31-Array of structures.pptx
 
Chapter 1 Basic Concepts
Chapter 1 Basic ConceptsChapter 1 Basic Concepts
Chapter 1 Basic Concepts
 
CUDA by Example : Parallel Programming in CUDA C : Notes
CUDA by Example : Parallel Programming in CUDA C : NotesCUDA by Example : Parallel Programming in CUDA C : Notes
CUDA by Example : Parallel Programming in CUDA C : Notes
 
A quick introduction to R
A quick introduction to RA quick introduction to R
A quick introduction to R
 

More from Md Polash

Lecture 1.pptx
Lecture 1.pptxLecture 1.pptx
Lecture 1.pptxMd Polash
 
Progressive collapse
Progressive collapseProgressive collapse
Progressive collapseMd Polash
 
HSU1EngineeringProfessionAB.ppt
HSU1EngineeringProfessionAB.pptHSU1EngineeringProfessionAB.ppt
HSU1EngineeringProfessionAB.pptMd Polash
 
civil_engineering.ppt
civil_engineering.pptcivil_engineering.ppt
civil_engineering.pptMd Polash
 
structure analysis.ppt
structure analysis.pptstructure analysis.ppt
structure analysis.pptMd Polash
 

More from Md Polash (6)

Lecture 1.pptx
Lecture 1.pptxLecture 1.pptx
Lecture 1.pptx
 
Progressive collapse
Progressive collapseProgressive collapse
Progressive collapse
 
bilow.pdf
bilow.pdfbilow.pdf
bilow.pdf
 
HSU1EngineeringProfessionAB.ppt
HSU1EngineeringProfessionAB.pptHSU1EngineeringProfessionAB.ppt
HSU1EngineeringProfessionAB.ppt
 
civil_engineering.ppt
civil_engineering.pptcivil_engineering.ppt
civil_engineering.ppt
 
structure analysis.ppt
structure analysis.pptstructure analysis.ppt
structure analysis.ppt
 

Recently uploaded

Pests of cotton_Borer_Pests_Binomics_Dr.UPR.pdf
Pests of cotton_Borer_Pests_Binomics_Dr.UPR.pdfPests of cotton_Borer_Pests_Binomics_Dr.UPR.pdf
Pests of cotton_Borer_Pests_Binomics_Dr.UPR.pdfPirithiRaju
 
Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...
Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...
Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...anilsa9823
 
9654467111 Call Girls In Raj Nagar Delhi Short 1500 Night 6000
9654467111 Call Girls In Raj Nagar Delhi Short 1500 Night 60009654467111 Call Girls In Raj Nagar Delhi Short 1500 Night 6000
9654467111 Call Girls In Raj Nagar Delhi Short 1500 Night 6000Sapana Sha
 
GBSN - Biochemistry (Unit 1)
GBSN - Biochemistry (Unit 1)GBSN - Biochemistry (Unit 1)
GBSN - Biochemistry (Unit 1)Areesha Ahmad
 
GBSN - Microbiology (Unit 1)
GBSN - Microbiology (Unit 1)GBSN - Microbiology (Unit 1)
GBSN - Microbiology (Unit 1)Areesha Ahmad
 
Zoology 4th semester series (krishna).pdf
Zoology 4th semester series (krishna).pdfZoology 4th semester series (krishna).pdf
Zoology 4th semester series (krishna).pdfSumit Kumar yadav
 
Pests of mustard_Identification_Management_Dr.UPR.pdf
Pests of mustard_Identification_Management_Dr.UPR.pdfPests of mustard_Identification_Management_Dr.UPR.pdf
Pests of mustard_Identification_Management_Dr.UPR.pdfPirithiRaju
 
Nanoparticles synthesis and characterization​ ​
Nanoparticles synthesis and characterization​  ​Nanoparticles synthesis and characterization​  ​
Nanoparticles synthesis and characterization​ ​kaibalyasahoo82800
 
DIFFERENCE IN BACK CROSS AND TEST CROSS
DIFFERENCE IN  BACK CROSS AND TEST CROSSDIFFERENCE IN  BACK CROSS AND TEST CROSS
DIFFERENCE IN BACK CROSS AND TEST CROSSLeenakshiTyagi
 
Presentation Vikram Lander by Vedansh Gupta.pptx
Presentation Vikram Lander by Vedansh Gupta.pptxPresentation Vikram Lander by Vedansh Gupta.pptx
Presentation Vikram Lander by Vedansh Gupta.pptxgindu3009
 
❤Jammu Kashmir Call Girls 8617697112 Personal Whatsapp Number 💦✅.
❤Jammu Kashmir Call Girls 8617697112 Personal Whatsapp Number 💦✅.❤Jammu Kashmir Call Girls 8617697112 Personal Whatsapp Number 💦✅.
❤Jammu Kashmir Call Girls 8617697112 Personal Whatsapp Number 💦✅.Nitya salvi
 
Chemistry 4th semester series (krishna).pdf
Chemistry 4th semester series (krishna).pdfChemistry 4th semester series (krishna).pdf
Chemistry 4th semester series (krishna).pdfSumit Kumar yadav
 
Botany krishna series 2nd semester Only Mcq type questions
Botany krishna series 2nd semester Only Mcq type questionsBotany krishna series 2nd semester Only Mcq type questions
Botany krishna series 2nd semester Only Mcq type questionsSumit Kumar yadav
 
Botany 4th semester series (krishna).pdf
Botany 4th semester series (krishna).pdfBotany 4th semester series (krishna).pdf
Botany 4th semester series (krishna).pdfSumit Kumar yadav
 
Recombination DNA Technology (Nucleic Acid Hybridization )
Recombination DNA Technology (Nucleic Acid Hybridization )Recombination DNA Technology (Nucleic Acid Hybridization )
Recombination DNA Technology (Nucleic Acid Hybridization )aarthirajkumar25
 
Spermiogenesis or Spermateleosis or metamorphosis of spermatid
Spermiogenesis or Spermateleosis or metamorphosis of spermatidSpermiogenesis or Spermateleosis or metamorphosis of spermatid
Spermiogenesis or Spermateleosis or metamorphosis of spermatidSarthak Sekhar Mondal
 
Chromatin Structure | EUCHROMATIN | HETEROCHROMATIN
Chromatin Structure | EUCHROMATIN | HETEROCHROMATINChromatin Structure | EUCHROMATIN | HETEROCHROMATIN
Chromatin Structure | EUCHROMATIN | HETEROCHROMATINsankalpkumarsahoo174
 
Formation of low mass protostars and their circumstellar disks
Formation of low mass protostars and their circumstellar disksFormation of low mass protostars and their circumstellar disks
Formation of low mass protostars and their circumstellar disksSérgio Sacani
 
Biological Classification BioHack (3).pdf
Biological Classification BioHack (3).pdfBiological Classification BioHack (3).pdf
Biological Classification BioHack (3).pdfmuntazimhurra
 

Recently uploaded (20)

Pests of cotton_Borer_Pests_Binomics_Dr.UPR.pdf
Pests of cotton_Borer_Pests_Binomics_Dr.UPR.pdfPests of cotton_Borer_Pests_Binomics_Dr.UPR.pdf
Pests of cotton_Borer_Pests_Binomics_Dr.UPR.pdf
 
The Philosophy of Science
The Philosophy of ScienceThe Philosophy of Science
The Philosophy of Science
 
Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...
Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...
Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...
 
9654467111 Call Girls In Raj Nagar Delhi Short 1500 Night 6000
9654467111 Call Girls In Raj Nagar Delhi Short 1500 Night 60009654467111 Call Girls In Raj Nagar Delhi Short 1500 Night 6000
9654467111 Call Girls In Raj Nagar Delhi Short 1500 Night 6000
 
GBSN - Biochemistry (Unit 1)
GBSN - Biochemistry (Unit 1)GBSN - Biochemistry (Unit 1)
GBSN - Biochemistry (Unit 1)
 
GBSN - Microbiology (Unit 1)
GBSN - Microbiology (Unit 1)GBSN - Microbiology (Unit 1)
GBSN - Microbiology (Unit 1)
 
Zoology 4th semester series (krishna).pdf
Zoology 4th semester series (krishna).pdfZoology 4th semester series (krishna).pdf
Zoology 4th semester series (krishna).pdf
 
Pests of mustard_Identification_Management_Dr.UPR.pdf
Pests of mustard_Identification_Management_Dr.UPR.pdfPests of mustard_Identification_Management_Dr.UPR.pdf
Pests of mustard_Identification_Management_Dr.UPR.pdf
 
Nanoparticles synthesis and characterization​ ​
Nanoparticles synthesis and characterization​  ​Nanoparticles synthesis and characterization​  ​
Nanoparticles synthesis and characterization​ ​
 
DIFFERENCE IN BACK CROSS AND TEST CROSS
DIFFERENCE IN  BACK CROSS AND TEST CROSSDIFFERENCE IN  BACK CROSS AND TEST CROSS
DIFFERENCE IN BACK CROSS AND TEST CROSS
 
Presentation Vikram Lander by Vedansh Gupta.pptx
Presentation Vikram Lander by Vedansh Gupta.pptxPresentation Vikram Lander by Vedansh Gupta.pptx
Presentation Vikram Lander by Vedansh Gupta.pptx
 
❤Jammu Kashmir Call Girls 8617697112 Personal Whatsapp Number 💦✅.
❤Jammu Kashmir Call Girls 8617697112 Personal Whatsapp Number 💦✅.❤Jammu Kashmir Call Girls 8617697112 Personal Whatsapp Number 💦✅.
❤Jammu Kashmir Call Girls 8617697112 Personal Whatsapp Number 💦✅.
 
Chemistry 4th semester series (krishna).pdf
Chemistry 4th semester series (krishna).pdfChemistry 4th semester series (krishna).pdf
Chemistry 4th semester series (krishna).pdf
 
Botany krishna series 2nd semester Only Mcq type questions
Botany krishna series 2nd semester Only Mcq type questionsBotany krishna series 2nd semester Only Mcq type questions
Botany krishna series 2nd semester Only Mcq type questions
 
Botany 4th semester series (krishna).pdf
Botany 4th semester series (krishna).pdfBotany 4th semester series (krishna).pdf
Botany 4th semester series (krishna).pdf
 
Recombination DNA Technology (Nucleic Acid Hybridization )
Recombination DNA Technology (Nucleic Acid Hybridization )Recombination DNA Technology (Nucleic Acid Hybridization )
Recombination DNA Technology (Nucleic Acid Hybridization )
 
Spermiogenesis or Spermateleosis or metamorphosis of spermatid
Spermiogenesis or Spermateleosis or metamorphosis of spermatidSpermiogenesis or Spermateleosis or metamorphosis of spermatid
Spermiogenesis or Spermateleosis or metamorphosis of spermatid
 
Chromatin Structure | EUCHROMATIN | HETEROCHROMATIN
Chromatin Structure | EUCHROMATIN | HETEROCHROMATINChromatin Structure | EUCHROMATIN | HETEROCHROMATIN
Chromatin Structure | EUCHROMATIN | HETEROCHROMATIN
 
Formation of low mass protostars and their circumstellar disks
Formation of low mass protostars and their circumstellar disksFormation of low mass protostars and their circumstellar disks
Formation of low mass protostars and their circumstellar disks
 
Biological Classification BioHack (3).pdf
Biological Classification BioHack (3).pdfBiological Classification BioHack (3).pdf
Biological Classification BioHack (3).pdf
 

04-struct-union.ppt

  • 1. Structures and Unions in C Alan L. Cox alc@rice.edu
  • 2. 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 Structures and Unions 2
  • 3. Cox Structures and Unions 3 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 = 2; date.day = 4; date.year = 2021;
  • 4. Cox Structures and Unions 4 Structure Representation & Size sizeof(struct …) = sum of sizeof(field) + alignment padding Processor- and compiler-specific 62 61 EF BE AD DE c1 c2 i padding struct CharCharInt { char c1; char c2; int i; } foo; foo.c1 = ’a’; foo.c2 = ’b’; foo.i = 0xDEADBEEF; x86 uses “little-endian” representation
  • 5. Cox Structures and Unions 5 Typedef Mechanism for creating new type names  New names are an alias for some other type  May improve the portability and/or clarity of the program typedef long int64_t; typedef struct ADate { int month; int day; int year; } Date; int64_t i = 100000000000; Date d = { 2, 4, 2021 }; Overload existing type names for portability Simplify complex type names
  • 6. Cox Structures and Unions 6 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
  • 7. Cox Structures and Unions 7 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); } Constant Array declaration Array index, then structure field
  • 8. Cox Structures and Unions 8 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(2, 4, 2021); create_date2(&today, 2, 4, 2021);
  • 9. Cox Structures and Unions 9 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, 2, 4, 2021); } today.month: today.day: today.year: 0x1000 0x1004 0x1008 month: 2 day: 4 year: 2021 0x30A0 0x30A4 0x30A8 d: 0x1000 0x3098 2 4 2021
  • 10. Cox Structures and Unions 10 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)
  • 11. Cox Structures and Unions 11 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 Structures and Unions 11
  • 12. Cox Structures and Unions 12 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
  • 13. Cox Structures and Unions 13 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 = ?
  • 14. Cox 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 bit_vec |= low_three_bits_mask; Setting bits: Result = ? 0…01 0111 == 0…01 0101 | 0…00 0111
  • 15. Cox 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; Clearing bits: Result = ? 0…01 0000 == 0…01 0101 & ~0…00 0111
  • 16. Cox Structures and Unions 16 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;
  • 17. Cox Structures and Unions 17 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;
  • 18. Cox Structures and Unions 18 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
  • 19. Cox Structures and Unions 19 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; };
  • 20. Cox Structures and Unions 20 Next Time Memory Allocation