SlideShare uma empresa Scribd logo
1 de 19
Structures and Unions in C
D.SEETHALAKSHMI
Assistant Professor of Computer Applications
Bon Secours College for Women
Thanjavur
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
Structures and Unions 2
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;
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
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
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
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
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);
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
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)
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!
Structures and Unions 11
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
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 = ?
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
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
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;
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;
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
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;
};

Mais conteúdo relacionado

Semelhante a Structure and Union.ppt

What's New in C++ 11/14?
What's New in C++ 11/14?What's New in C++ 11/14?
What's New in C++ 11/14?Dina Goldshtein
 
Data structure manual
Data structure manualData structure manual
Data structure manualsameer farooq
 
C programming session 13
C programming session 13C programming session 13
C programming session 13AjayBahoriya
 
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
 
(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
 
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
 
Excel DATEDIFF Function
Excel DATEDIFF FunctionExcel DATEDIFF Function
Excel DATEDIFF FunctionExcel
 
CHAPTER -4-class and structure.pptx
CHAPTER -4-class and structure.pptxCHAPTER -4-class and structure.pptx
CHAPTER -4-class and structure.pptxGebruGetachew2
 
13 -times_and_dates
13  -times_and_dates13  -times_and_dates
13 -times_and_datesHector Garzo
 
introductory concepts
introductory conceptsintroductory concepts
introductory conceptsWalepak Ubi
 
C programming session 09
C programming session 09C programming session 09
C programming session 09Dushmanta Nath
 
Lesson 21. Pattern 13. Data alignment
Lesson 21. Pattern 13. Data alignmentLesson 21. Pattern 13. Data alignment
Lesson 21. Pattern 13. Data alignmentPVS-Studio
 
"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
 

Semelhante a Structure and Union.ppt (20)

What's New in C++ 11/14?
What's New in C++ 11/14?What's New in C++ 11/14?
What's New in C++ 11/14?
 
Data structure manual
Data structure manualData structure manual
Data structure manual
 
C programming session 13
C programming session 13C programming session 13
C programming session 13
 
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
 
(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
 
C programming & data structure [arrays & pointers]
C programming & data structure   [arrays & pointers]C programming & data structure   [arrays & pointers]
C programming & data structure [arrays & pointers]
 
Excel DATEDIFF Function
Excel DATEDIFF FunctionExcel DATEDIFF Function
Excel DATEDIFF Function
 
CHAPTER -4-class and structure.pptx
CHAPTER -4-class and structure.pptxCHAPTER -4-class and structure.pptx
CHAPTER -4-class and structure.pptx
 
Structures_Final_KLE (2).pptx
Structures_Final_KLE (2).pptxStructures_Final_KLE (2).pptx
Structures_Final_KLE (2).pptx
 
ELAVARASAN.pdf
ELAVARASAN.pdfELAVARASAN.pdf
ELAVARASAN.pdf
 
Structures
StructuresStructures
Structures
 
Structures
StructuresStructures
Structures
 
13 -times_and_dates
13  -times_and_dates13  -times_and_dates
13 -times_and_dates
 
introductory concepts
introductory conceptsintroductory concepts
introductory concepts
 
C programming session 09
C programming session 09C programming session 09
C programming session 09
 
structure1.pdf
structure1.pdfstructure1.pdf
structure1.pdf
 
Lesson 21. Pattern 13. Data alignment
Lesson 21. Pattern 13. Data alignmentLesson 21. Pattern 13. Data alignment
Lesson 21. Pattern 13. Data alignment
 
"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
 

Mais de SeethaDinesh

Input Devices.pptx
Input Devices.pptxInput Devices.pptx
Input Devices.pptxSeethaDinesh
 
Generations of Computers.ppt
Generations of Computers.pptGenerations of Computers.ppt
Generations of Computers.pptSeethaDinesh
 
Inheritance in java.ppt
Inheritance in java.pptInheritance in java.ppt
Inheritance in java.pptSeethaDinesh
 
Arrays in JAVA.ppt
Arrays in JAVA.pptArrays in JAVA.ppt
Arrays in JAVA.pptSeethaDinesh
 
PROGRAMMING IN JAVA unit 1.pptx
PROGRAMMING IN JAVA unit 1.pptxPROGRAMMING IN JAVA unit 1.pptx
PROGRAMMING IN JAVA unit 1.pptxSeethaDinesh
 
Cloud Computing Basics.pptx
Cloud Computing Basics.pptxCloud Computing Basics.pptx
Cloud Computing Basics.pptxSeethaDinesh
 
unit 5 stack & queue.ppt
unit 5 stack & queue.pptunit 5 stack & queue.ppt
unit 5 stack & queue.pptSeethaDinesh
 
Greedy_Backtracking graph coloring.ppt
Greedy_Backtracking graph coloring.pptGreedy_Backtracking graph coloring.ppt
Greedy_Backtracking graph coloring.pptSeethaDinesh
 
Shortest Path Problem.docx
Shortest Path Problem.docxShortest Path Problem.docx
Shortest Path Problem.docxSeethaDinesh
 
BINARY TREE REPRESENTATION.ppt
BINARY TREE REPRESENTATION.pptBINARY TREE REPRESENTATION.ppt
BINARY TREE REPRESENTATION.pptSeethaDinesh
 
NME WPI UNIt 3.pptx
NME WPI UNIt 3.pptxNME WPI UNIt 3.pptx
NME WPI UNIt 3.pptxSeethaDinesh
 
NME UNIT I & II MATERIAL.pdf
NME UNIT I & II MATERIAL.pdfNME UNIT I & II MATERIAL.pdf
NME UNIT I & II MATERIAL.pdfSeethaDinesh
 
graphtraversals.pdf
graphtraversals.pdfgraphtraversals.pdf
graphtraversals.pdfSeethaDinesh
 

Mais de SeethaDinesh (20)

Input Devices.pptx
Input Devices.pptxInput Devices.pptx
Input Devices.pptx
 
Generations of Computers.ppt
Generations of Computers.pptGenerations of Computers.ppt
Generations of Computers.ppt
 
Inheritance in java.ppt
Inheritance in java.pptInheritance in java.ppt
Inheritance in java.ppt
 
Arrays in JAVA.ppt
Arrays in JAVA.pptArrays in JAVA.ppt
Arrays in JAVA.ppt
 
PROGRAMMING IN JAVA unit 1.pptx
PROGRAMMING IN JAVA unit 1.pptxPROGRAMMING IN JAVA unit 1.pptx
PROGRAMMING IN JAVA unit 1.pptx
 
Cloud Computing Basics.pptx
Cloud Computing Basics.pptxCloud Computing Basics.pptx
Cloud Computing Basics.pptx
 
unit 5 stack & queue.ppt
unit 5 stack & queue.pptunit 5 stack & queue.ppt
unit 5 stack & queue.ppt
 
Greedy_Backtracking graph coloring.ppt
Greedy_Backtracking graph coloring.pptGreedy_Backtracking graph coloring.ppt
Greedy_Backtracking graph coloring.ppt
 
Shortest Path Problem.docx
Shortest Path Problem.docxShortest Path Problem.docx
Shortest Path Problem.docx
 
BINARY TREE REPRESENTATION.ppt
BINARY TREE REPRESENTATION.pptBINARY TREE REPRESENTATION.ppt
BINARY TREE REPRESENTATION.ppt
 
NME UNIT II.ppt
NME UNIT II.pptNME UNIT II.ppt
NME UNIT II.ppt
 
DS UNIT 1.pdf
DS UNIT 1.pdfDS UNIT 1.pdf
DS UNIT 1.pdf
 
Basics of C.ppt
Basics of C.pptBasics of C.ppt
Basics of C.ppt
 
chapter 1.pptx
chapter 1.pptxchapter 1.pptx
chapter 1.pptx
 
DW unit 3.pptx
DW unit 3.pptxDW unit 3.pptx
DW unit 3.pptx
 
DW unit 2.pdf
DW unit 2.pdfDW unit 2.pdf
DW unit 2.pdf
 
DW Unit 1.pdf
DW Unit 1.pdfDW Unit 1.pdf
DW Unit 1.pdf
 
NME WPI UNIt 3.pptx
NME WPI UNIt 3.pptxNME WPI UNIt 3.pptx
NME WPI UNIt 3.pptx
 
NME UNIT I & II MATERIAL.pdf
NME UNIT I & II MATERIAL.pdfNME UNIT I & II MATERIAL.pdf
NME UNIT I & II MATERIAL.pdf
 
graphtraversals.pdf
graphtraversals.pdfgraphtraversals.pdf
graphtraversals.pdf
 

Último

What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxnelietumpap1
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 

Último (20)

What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptx
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
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🔝
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 

Structure and Union.ppt

  • 1. Structures and Unions in C D.SEETHALAKSHMI Assistant Professor of Computer Applications Bon Secours College for Women Thanjavur
  • 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 Structures and Unions 2
  • 3. 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. 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. 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. 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. 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. 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. 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. 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. 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! Structures and Unions 11
  • 12. 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. 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. 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. 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. 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. 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. 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. 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; };