SlideShare una empresa de Scribd logo
1 de 50
C Programming : User-defined data types
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Perundurai, Erode, Tamilnadu, India
Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018.
20CST11 – Problem Solving and Programming
3/10/2021 5.1 Structure and Union 2
Syllabus
Contents
• There are 4 types of user-defined data types.
1. Structure (struct)
 Structure basics
 Declaring and defining a structure
 Attributes of structures
 Nested structures
 Arrays as structure members
 Arrays of structure
 Passing structures as arguments to functions
 Bit Fields
2. Unions (union)
3. Enumerated type (enum)
4. Type definition (typedef)
3/10/2021 5.1 Structure and Union 3
Structure Basics
• C offers a basket of data types for handling different
levels of complexity in the organization of data.
• The primary data types (like int and float) are meant
for using simple and small amounts of data.
• The array is offered as a derived data type for handling
a group of data items of the same type.
• Real-life situations often involve the use of
heterogeneous data that need a mix of data types to
be handled as a single unit.
• Structures and unions meet this requirement perfectly.
3/10/2021 5.1 Structure and Union 4
Structure Basics
• A group of data items are often logically related to one
another.
• For instance,
– the attributes of an employee include the name, address,
date of birth, salary, and so forth.
• A structure is a data type that is designed by the user.
• However, unlike the other data types, a structure
variable is based on a template that must be created
first.
• Each member of the structure is accessed by the
notation structure.member, and can be used in
practically the same way as a variable.
3/10/2021 5.1 Structure and Union 5
Declaring and Defining a Structure
• a structure variable is created in two steps
which may or may not be combined:
– Declare the structure to create a template which
specifies the components of the structure.
• Declaration simply makes type information available
to the compiler. However, the compiler doesn’t
allocate memory by seeing the declaration.
– Define a variable that conforms to the template.
• The compiler allocates memory for the variable and
creates an instance of the template.
3/10/2021 5.1 Structure and Union 6
Declaring and Defining a Structure
• Declaration uses the struct keyword.
• The following generalized syntax declares a structure
named struct_name.
• The syntax of the definition also specifies the keyword
struct, the structure tag (struct_name) and the
variable name (struct_var).
3/10/2021 5.1 Structure and Union 7
Example
3/10/2021 5.1 Structure and Union 8
Accessing Members of a Structure
3/10/2021 5.1 Structure and Union 9
Combining Declaration, Definition and Initialization
• For an initialized structure, the variable name is followed by an = and a list of
comma-delimited values enclosed by curly braces.
• These initializers obviously must be provided in the right order.
• In Form 2, “Beethoven” is assigned to title and 3 to qty.
• You can create multiple variables and initialize them at the same time.
• Like with arrays, you can partially initialize a structure. If you initialize only
title, the remaining members, qty and price, are automatically assigned zeroes
• By default, uninitialized structures have junk values unless they are global.
3/10/2021 5.1 Structure and Union 10
Declaring without Structure Tag
• If declaration and definition are combined, the structure
tag can be omitted.
• This is usually done when no more structure variables of
that type require to be defined later in the program.
• You can’t subsequently create any more variables of this
type.
3/10/2021 5.1 Structure and Union 11
3/10/2021 5.1 Structure and Union 12
3/10/2021 5.1 Structure and Union 13
Memory Layout of Members of music_cd
• Note that sizeof computes the total memory
occupied by a structure.
• This is not necessarily the sum of the sizes of the
members.
• Thus, on this machine having a 4-byte word.
– title occupies 28 bytes (7 words) even though it uses
27 of them.
– qty and price individually occupy an entire word (4
bytes each), but qty uses two of these bytes.
– disk1 thus needs 33 bytes (27 + 2 + 4) but it actually
occupies 36 bytes.
3/10/2021 5.1 Structure and Union 14
Memory Layout of Members of music_cd
• Alignment issues related to structures lead to
the creation of slack bytes or holes in the
allocated memory segment.
3/10/2021 5.1 Structure and Union 15
Attributes Of Structures
• (1) There are no name conflicts between
structure templates, their instantiated
variables and members.
3/10/2021 5.1 Structure and Union 16
Attributes Of Structures
• (2) The =, dot, -> and & are the only operators
that can be used on structures.
• (3) A structure can be copied to another
structure provided both objects are based on
the same template.
• This feature is not available with arrays; all
array elements have to be copied individually
3/10/2021 5.1 Structure and Union 17
Attributes Of Structures
• (4) No arithmetic, relational or logical operations can be
performed on structures even when the operation logically makes
sense.
• (5) It is not possible to compare two structures using a single
operator even though such comparison could be logically
meaningful.
– Each member has to be compared individually as shown by the
following code.
– If a structure contains 20 members, you need to use 20 relational
expressions to test for equality.
– Unfortunately, C doesn’t support a better option.
3/10/2021 5.1 Structure and Union 18
3/10/2021 5.1 Structure and Union 19
Attributes Of Structures
• (6) When a structure is passed by name as an
argument to a function, the entire structure is
copied inside the function.
• (7) A member of a structure can contain a
reference to another structure of the same
type.
– This property of self-referential structures is used
for creating linked lists.
3/10/2021 5.1 Structure and Union 20
Nested Structures
• A structure member can have any data type—including
another structure (but not of the same type though).
• The inner structure can contain another structure and
so on.
• C supports nested structures and the following outer
structure named student contains an inner structure
named dt_birth as one of its four members.
3/10/2021 5.1 Structure and Union 21
Example
3/10/2021 5.1 Structure and Union 22
Initializing a Nested Structure
• When it comes to initialization, nested
structures resemble multi-dimensional arrays.
• For every level of nesting, a set of inner
braces have to be used for members of the
inner structure.
3/10/2021 5.1 Structure and Union 23
Accessing Members
• A member of an inner structure is connected
by a dot to its immediately enclosing
structure, which is connected by another dot
to the outer structure.
3/10/2021 5.1 Structure and Union 24
Arrays as structure members
3/10/2021 5.1 Structure and Union 25
Arrays Of Structures
• We used two structure variables, stud1 and stud2, to
handle data of two students.
• This technique won’t work with 500 students.
• C supports an array of structures, whose definition
may or may not be combined with the declaration of
the structure.
• The following statement defines an array of type struct
student that can hold 50 sets (or records) of student
data.
3/10/2021 5.1 Structure and Union 26
Arrays Of Structures
• Alternatively, you can separate the declaration and
definition.
• You can also use typedef to replace struct student with
STUDENT.
3/10/2021 5.1 Structure and Union 27
Arrays Of Structures
3/10/2021 5.1 Structure and Union 28
Structures in functions
3/10/2021 5.1 Structure and Union 29
Structures in functions
• A function using a structure as argument
copies the entire structure.
• If the structure contains an array, it too will be
copied.
• A program may run out of memory when
using structures as arguments.
• A structure containing numerous members
and large arrays can lead to stack overflow
and cause the program to abort
3/10/2021 5.1 Structure and Union 30
3/10/2021 5.1 Structure and Union 31
3/10/2021 5.1 Structure and Union 32
Bit fields
• Have our programs wasted memory?
– Yes, in many cases they have.
• We used 2-byte short integers to store each
component of a date when a few bits would
have sufficed.
• We also wasted 15 bits of the 16 available in
short to set a flag to 0 and 1
3/10/2021 5.1 Structure and Union 33
Bit fields
• It’s time to know that C supports a memory saving
feature—the bit field.
• It can be used with the right number of bits, rather
than bytes, to store data.
• One or two bits are adequate to represent the sex.
• while six or seven bits are good enough to represent
the age.
• Bit fields can be used only as structure members.
• Properly sized bit fields prevent both data overflow
and memory wastage.
3/10/2021 5.1 Structure and Union 34
Example
• The first two members, id and age, are bit fields.
• The declaration of a bit field specifies an int (signed or
unsigned), followed by the member name, a colon and the
number of allocated bits.
• Here, id and age occupy 10 and 6 bits, respectively.
• This means that the maximum values of id and age are
restricted to 1023 and 63, respectively.
• sizeof evaluates the size of emp to 32.
• A similar structure using two short variables for id and age
would occupy 34 bytes.
3/10/2021 5.1 Structure and Union 35
Unions
• When searching a database using a person’s id, you must
have often wanted to search by name as well.
• That is possible if the two attributes are held in a union, a
data type that resembles a structure in form.
• A union comprises two or more members that share the
same memory, with the most recent assignment to a
member being active at any instant.
• You can define a union with many members, but only one
member can contain a value at any given time.
• Unions provide an efficient way of using the same
memory location for multiple purposes.
• Consider the following declaration and definition of a union
3/10/2021 5.1 Structure and Union 36
Unions
3/10/2021 5.1 Structure and Union 37
• A union is declared, defined and accessed exactly
like a structure.
• The previous statement declares a two-member
union named uemp and simultaneously defines
the union variable u.
• The members are accessed as u.emp_id and
u.name.
• However, both members share a single memory
region and you can correctly access only one
member at a time—the one that was last
assigned.
Unions
3/10/2021 5.1 Structure and Union 38
Unique Attributes of Unions
• (1) All members of a union can’t be initialized
simultaneously.
• (2) The size of a union is determined by the size of the
member having the largest footprint in memory. (For
uemp, this would be 30, the size of the name field).
• (3) The compiler doesn’t output an error when you
access a member that was not the last one to be
assigned. A programmer must keep track of the
member that is active at any instant.
• (4) You can use a union to assign a value to a member
and read it back using a different member.
3/10/2021 5.1 Structure and Union 39
Unions
• A union can easily determine whether a
machine is little-endian or big-endian.
• In a big-endian machine, the most significant
bit is stored first while the reverse is true for
little-endian machines.
• However, unions are mainly used as memory-
saving objects.
3/10/2021 5.1 Structure and Union 40
Example
3/10/2021 5.1 Structure and Union 41
Example
3/10/2021 5.1 Structure and Union 42
Difference between Structure and Union
3/10/2021 5.1 Structure and Union 43
The enumerated type (enum)
• We have used symbolic constants to represent
integers using the #define feature of the
preprocessor.
• C also supports the user-defined enumeration
data type that assigns names to a set of
integer values called enumerators.
• For instance, you can create a set of named
constants using the enum keyword.
3/10/2021 5.1 Structure and Union 44
• This statement creates a set of enumerated
integer values which, by default, begin with 0.
• YES evaluates to 0, while NO and CANT_SAY
have the values 1 and 2, respectively.
• If this declaration is made before main, you
can use NO to represent 1 anywhere in the
program.
3/10/2021 5.1 Structure and Union 45
• You can now create one or more enum
variables of type eday.
3/10/2021 5.1 Structure and Union 46
3/10/2021 5.1 Structure and Union 47
Abbreviating a Data Type : The typedef Feature
• The typedef keyword is used to abbreviate
the names of data types.
• Using A Data type LL instead of long long
involves less typing.
• The syntax of typedef is simple; follow
typedef with the existing data type and its
proposed synonym.
3/10/2021 5.1 Structure and Union 48
Example
3/10/2021 5.1 Structure and Union 49
Thank you
3/10/2021 5.1 Structure and Union 50

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

Two dimensional array
Two dimensional arrayTwo dimensional array
Two dimensional array
 
Structure in c
Structure in cStructure in c
Structure in c
 
Structures and Pointers
Structures and PointersStructures and Pointers
Structures and Pointers
 
Union in c language
Union  in c languageUnion  in c language
Union in c language
 
C Language
C LanguageC Language
C Language
 
What is identifier c programming
What is identifier c programmingWhat is identifier c programming
What is identifier c programming
 
Introduction to c++ ppt
Introduction to c++ pptIntroduction to c++ ppt
Introduction to c++ ppt
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
 
INTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMINGINTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMING
 
Inline function
Inline functionInline function
Inline function
 
Bitwise operators
Bitwise operatorsBitwise operators
Bitwise operators
 
structure and union
structure and unionstructure and union
structure and union
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
C by balaguruswami - e.balagurusamy
C   by balaguruswami - e.balagurusamyC   by balaguruswami - e.balagurusamy
C by balaguruswami - e.balagurusamy
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Conditional Statement in C Language
Conditional Statement in C LanguageConditional Statement in C Language
Conditional Statement in C Language
 
Structure & union
Structure & unionStructure & union
Structure & union
 
Loops in C Programming Language
Loops in C Programming LanguageLoops in C Programming Language
Loops in C Programming Language
 
Structures
StructuresStructures
Structures
 

Similar a C Programming: Structure and Union

Intake 38 data access 4
Intake 38 data access 4Intake 38 data access 4
Intake 38 data access 4Mahmoud Ouf
 
Unit 2_DBMS_10.2.22.pptx
Unit 2_DBMS_10.2.22.pptxUnit 2_DBMS_10.2.22.pptx
Unit 2_DBMS_10.2.22.pptxMaryJoseph79
 
Database concepts
Database conceptsDatabase concepts
Database conceptsJames Wong
 
Database concepts
Database conceptsDatabase concepts
Database conceptsDavid Hoen
 
Database concepts
Database conceptsDatabase concepts
Database conceptsFraboni Ec
 
Database concepts
Database conceptsDatabase concepts
Database conceptsTony Nguyen
 
PP DBMS - 1 (1).pptx
PP DBMS - 1 (1).pptxPP DBMS - 1 (1).pptx
PP DBMS - 1 (1).pptxskilljiolms
 
PP DBMS - 1 (2).pptx
PP DBMS - 1 (2).pptxPP DBMS - 1 (2).pptx
PP DBMS - 1 (2).pptxskilljiolms
 
PP DBMS - 1 (1).pptx
PP DBMS - 1 (1).pptxPP DBMS - 1 (1).pptx
PP DBMS - 1 (1).pptxskilljiolms
 
ADBMS ALL 2069-73 [CSITauthority.blogspot.com].pdf
ADBMS ALL 2069-73 [CSITauthority.blogspot.com].pdfADBMS ALL 2069-73 [CSITauthority.blogspot.com].pdf
ADBMS ALL 2069-73 [CSITauthority.blogspot.com].pdfarvind pandey
 
DS-UNIT 1 FINAL (2).pptx
DS-UNIT 1 FINAL (2).pptxDS-UNIT 1 FINAL (2).pptx
DS-UNIT 1 FINAL (2).pptxprakashvs7
 
Data Structures_Introduction
Data Structures_IntroductionData Structures_Introduction
Data Structures_IntroductionThenmozhiK5
 
SADP PPTs of all modules - Shanthi D.L.pdf
SADP PPTs of all modules - Shanthi D.L.pdfSADP PPTs of all modules - Shanthi D.L.pdf
SADP PPTs of all modules - Shanthi D.L.pdfB.T.L.I.T
 

Similar a C Programming: Structure and Union (20)

Intake 38 data access 4
Intake 38 data access 4Intake 38 data access 4
Intake 38 data access 4
 
C- language Lecture 7
C- language Lecture 7C- language Lecture 7
C- language Lecture 7
 
Intake 37 ef1
Intake 37 ef1Intake 37 ef1
Intake 37 ef1
 
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
 
Unit 2_DBMS_10.2.22.pptx
Unit 2_DBMS_10.2.22.pptxUnit 2_DBMS_10.2.22.pptx
Unit 2_DBMS_10.2.22.pptx
 
Database concepts
Database conceptsDatabase concepts
Database concepts
 
Database concepts
Database conceptsDatabase concepts
Database concepts
 
Database concepts
Database conceptsDatabase concepts
Database concepts
 
Database concepts
Database conceptsDatabase concepts
Database concepts
 
Database concepts
Database conceptsDatabase concepts
Database concepts
 
Database concepts
Database conceptsDatabase concepts
Database concepts
 
Database concepts
Database conceptsDatabase concepts
Database concepts
 
PP DBMS - 1 (1).pptx
PP DBMS - 1 (1).pptxPP DBMS - 1 (1).pptx
PP DBMS - 1 (1).pptx
 
PP DBMS - 1 (2).pptx
PP DBMS - 1 (2).pptxPP DBMS - 1 (2).pptx
PP DBMS - 1 (2).pptx
 
PP DBMS - 1 (1).pptx
PP DBMS - 1 (1).pptxPP DBMS - 1 (1).pptx
PP DBMS - 1 (1).pptx
 
DBMS topic in PU
DBMS topic in PUDBMS topic in PU
DBMS topic in PU
 
ADBMS ALL 2069-73 [CSITauthority.blogspot.com].pdf
ADBMS ALL 2069-73 [CSITauthority.blogspot.com].pdfADBMS ALL 2069-73 [CSITauthority.blogspot.com].pdf
ADBMS ALL 2069-73 [CSITauthority.blogspot.com].pdf
 
DS-UNIT 1 FINAL (2).pptx
DS-UNIT 1 FINAL (2).pptxDS-UNIT 1 FINAL (2).pptx
DS-UNIT 1 FINAL (2).pptx
 
Data Structures_Introduction
Data Structures_IntroductionData Structures_Introduction
Data Structures_Introduction
 
SADP PPTs of all modules - Shanthi D.L.pdf
SADP PPTs of all modules - Shanthi D.L.pdfSADP PPTs of all modules - Shanthi D.L.pdf
SADP PPTs of all modules - Shanthi D.L.pdf
 

Más de Selvaraj Seerangan

Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...
Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...
Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...Selvaraj Seerangan
 
END SEM _ Design Thinking _ 16 Templates.pptx
END SEM _ Design Thinking _ 16 Templates.pptxEND SEM _ Design Thinking _ 16 Templates.pptx
END SEM _ Design Thinking _ 16 Templates.pptxSelvaraj Seerangan
 
Design Thinking _ Complete Templates.pptx
Design Thinking _ Complete Templates.pptxDesign Thinking _ Complete Templates.pptx
Design Thinking _ Complete Templates.pptxSelvaraj Seerangan
 
CAT 3 _ List of Templates.pptx
CAT 3 _ List of Templates.pptxCAT 3 _ List of Templates.pptx
CAT 3 _ List of Templates.pptxSelvaraj Seerangan
 
[PPT] _ Unit 3 _ Experiment.pptx
[PPT] _ Unit 3 _ Experiment.pptx[PPT] _ Unit 3 _ Experiment.pptx
[PPT] _ Unit 3 _ Experiment.pptxSelvaraj Seerangan
 
CAT 2 _ List of Templates.pptx
CAT 2 _ List of Templates.pptxCAT 2 _ List of Templates.pptx
CAT 2 _ List of Templates.pptxSelvaraj Seerangan
 
Design Thinking - Empathize Phase
Design Thinking - Empathize PhaseDesign Thinking - Empathize Phase
Design Thinking - Empathize PhaseSelvaraj Seerangan
 
18CSL51 - Network Lab Manual.pdf
18CSL51 - Network Lab Manual.pdf18CSL51 - Network Lab Manual.pdf
18CSL51 - Network Lab Manual.pdfSelvaraj Seerangan
 
CAT 1 _ List of Templates.pptx
CAT 1 _ List of Templates.pptxCAT 1 _ List of Templates.pptx
CAT 1 _ List of Templates.pptxSelvaraj Seerangan
 
[PPT] _ UNIT 1 _ COMPLETE.pptx
[PPT] _ UNIT 1 _ COMPLETE.pptx[PPT] _ UNIT 1 _ COMPLETE.pptx
[PPT] _ UNIT 1 _ COMPLETE.pptxSelvaraj Seerangan
 
[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf
[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf
[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdfSelvaraj Seerangan
 

Más de Selvaraj Seerangan (20)

Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...
Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...
Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...
 
Unit 5 _ Fog Computing .pdf
Unit 5 _ Fog Computing .pdfUnit 5 _ Fog Computing .pdf
Unit 5 _ Fog Computing .pdf
 
CAT III Answer Key.pdf
CAT III Answer Key.pdfCAT III Answer Key.pdf
CAT III Answer Key.pdf
 
END SEM _ Design Thinking _ 16 Templates.pptx
END SEM _ Design Thinking _ 16 Templates.pptxEND SEM _ Design Thinking _ 16 Templates.pptx
END SEM _ Design Thinking _ 16 Templates.pptx
 
Design Thinking _ Complete Templates.pptx
Design Thinking _ Complete Templates.pptxDesign Thinking _ Complete Templates.pptx
Design Thinking _ Complete Templates.pptx
 
CAT 3 _ List of Templates.pptx
CAT 3 _ List of Templates.pptxCAT 3 _ List of Templates.pptx
CAT 3 _ List of Templates.pptx
 
[PPT] _ Unit 5 _ Evolve.pptx
[PPT] _ Unit 5 _ Evolve.pptx[PPT] _ Unit 5 _ Evolve.pptx
[PPT] _ Unit 5 _ Evolve.pptx
 
[PPT] _ Unit 4 _ Engage.pptx
[PPT] _ Unit 4 _ Engage.pptx[PPT] _ Unit 4 _ Engage.pptx
[PPT] _ Unit 4 _ Engage.pptx
 
[PPT] _ Unit 3 _ Experiment.pptx
[PPT] _ Unit 3 _ Experiment.pptx[PPT] _ Unit 3 _ Experiment.pptx
[PPT] _ Unit 3 _ Experiment.pptx
 
CAT 2 _ List of Templates.pptx
CAT 2 _ List of Templates.pptxCAT 2 _ List of Templates.pptx
CAT 2 _ List of Templates.pptx
 
Design Thinking - Empathize Phase
Design Thinking - Empathize PhaseDesign Thinking - Empathize Phase
Design Thinking - Empathize Phase
 
CAT-II Answer Key.pdf
CAT-II Answer Key.pdfCAT-II Answer Key.pdf
CAT-II Answer Key.pdf
 
PSP LAB MANUAL.pdf
PSP LAB MANUAL.pdfPSP LAB MANUAL.pdf
PSP LAB MANUAL.pdf
 
18CSL51 - Network Lab Manual.pdf
18CSL51 - Network Lab Manual.pdf18CSL51 - Network Lab Manual.pdf
18CSL51 - Network Lab Manual.pdf
 
DS LAB MANUAL.pdf
DS LAB MANUAL.pdfDS LAB MANUAL.pdf
DS LAB MANUAL.pdf
 
CAT 1 _ List of Templates.pptx
CAT 1 _ List of Templates.pptxCAT 1 _ List of Templates.pptx
CAT 1 _ List of Templates.pptx
 
[PPT] _ UNIT 1 _ COMPLETE.pptx
[PPT] _ UNIT 1 _ COMPLETE.pptx[PPT] _ UNIT 1 _ COMPLETE.pptx
[PPT] _ UNIT 1 _ COMPLETE.pptx
 
CAT-1 Answer Key.doc
CAT-1 Answer Key.docCAT-1 Answer Key.doc
CAT-1 Answer Key.doc
 
Unit 3 Complete.pptx
Unit 3 Complete.pptxUnit 3 Complete.pptx
Unit 3 Complete.pptx
 
[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf
[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf
[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf
 

Último

Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxdhanalakshmis0310
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docxPoojaSen20
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 

Último (20)

Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 

C Programming: Structure and Union

  • 1. C Programming : User-defined data types By Mr.S.Selvaraj Asst. Professor (SRG) / CSE Kongu Engineering College Perundurai, Erode, Tamilnadu, India Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018.
  • 2. 20CST11 – Problem Solving and Programming 3/10/2021 5.1 Structure and Union 2 Syllabus
  • 3. Contents • There are 4 types of user-defined data types. 1. Structure (struct)  Structure basics  Declaring and defining a structure  Attributes of structures  Nested structures  Arrays as structure members  Arrays of structure  Passing structures as arguments to functions  Bit Fields 2. Unions (union) 3. Enumerated type (enum) 4. Type definition (typedef) 3/10/2021 5.1 Structure and Union 3
  • 4. Structure Basics • C offers a basket of data types for handling different levels of complexity in the organization of data. • The primary data types (like int and float) are meant for using simple and small amounts of data. • The array is offered as a derived data type for handling a group of data items of the same type. • Real-life situations often involve the use of heterogeneous data that need a mix of data types to be handled as a single unit. • Structures and unions meet this requirement perfectly. 3/10/2021 5.1 Structure and Union 4
  • 5. Structure Basics • A group of data items are often logically related to one another. • For instance, – the attributes of an employee include the name, address, date of birth, salary, and so forth. • A structure is a data type that is designed by the user. • However, unlike the other data types, a structure variable is based on a template that must be created first. • Each member of the structure is accessed by the notation structure.member, and can be used in practically the same way as a variable. 3/10/2021 5.1 Structure and Union 5
  • 6. Declaring and Defining a Structure • a structure variable is created in two steps which may or may not be combined: – Declare the structure to create a template which specifies the components of the structure. • Declaration simply makes type information available to the compiler. However, the compiler doesn’t allocate memory by seeing the declaration. – Define a variable that conforms to the template. • The compiler allocates memory for the variable and creates an instance of the template. 3/10/2021 5.1 Structure and Union 6
  • 7. Declaring and Defining a Structure • Declaration uses the struct keyword. • The following generalized syntax declares a structure named struct_name. • The syntax of the definition also specifies the keyword struct, the structure tag (struct_name) and the variable name (struct_var). 3/10/2021 5.1 Structure and Union 7
  • 9. Accessing Members of a Structure 3/10/2021 5.1 Structure and Union 9
  • 10. Combining Declaration, Definition and Initialization • For an initialized structure, the variable name is followed by an = and a list of comma-delimited values enclosed by curly braces. • These initializers obviously must be provided in the right order. • In Form 2, “Beethoven” is assigned to title and 3 to qty. • You can create multiple variables and initialize them at the same time. • Like with arrays, you can partially initialize a structure. If you initialize only title, the remaining members, qty and price, are automatically assigned zeroes • By default, uninitialized structures have junk values unless they are global. 3/10/2021 5.1 Structure and Union 10
  • 11. Declaring without Structure Tag • If declaration and definition are combined, the structure tag can be omitted. • This is usually done when no more structure variables of that type require to be defined later in the program. • You can’t subsequently create any more variables of this type. 3/10/2021 5.1 Structure and Union 11
  • 12. 3/10/2021 5.1 Structure and Union 12
  • 13. 3/10/2021 5.1 Structure and Union 13
  • 14. Memory Layout of Members of music_cd • Note that sizeof computes the total memory occupied by a structure. • This is not necessarily the sum of the sizes of the members. • Thus, on this machine having a 4-byte word. – title occupies 28 bytes (7 words) even though it uses 27 of them. – qty and price individually occupy an entire word (4 bytes each), but qty uses two of these bytes. – disk1 thus needs 33 bytes (27 + 2 + 4) but it actually occupies 36 bytes. 3/10/2021 5.1 Structure and Union 14
  • 15. Memory Layout of Members of music_cd • Alignment issues related to structures lead to the creation of slack bytes or holes in the allocated memory segment. 3/10/2021 5.1 Structure and Union 15
  • 16. Attributes Of Structures • (1) There are no name conflicts between structure templates, their instantiated variables and members. 3/10/2021 5.1 Structure and Union 16
  • 17. Attributes Of Structures • (2) The =, dot, -> and & are the only operators that can be used on structures. • (3) A structure can be copied to another structure provided both objects are based on the same template. • This feature is not available with arrays; all array elements have to be copied individually 3/10/2021 5.1 Structure and Union 17
  • 18. Attributes Of Structures • (4) No arithmetic, relational or logical operations can be performed on structures even when the operation logically makes sense. • (5) It is not possible to compare two structures using a single operator even though such comparison could be logically meaningful. – Each member has to be compared individually as shown by the following code. – If a structure contains 20 members, you need to use 20 relational expressions to test for equality. – Unfortunately, C doesn’t support a better option. 3/10/2021 5.1 Structure and Union 18
  • 19. 3/10/2021 5.1 Structure and Union 19
  • 20. Attributes Of Structures • (6) When a structure is passed by name as an argument to a function, the entire structure is copied inside the function. • (7) A member of a structure can contain a reference to another structure of the same type. – This property of self-referential structures is used for creating linked lists. 3/10/2021 5.1 Structure and Union 20
  • 21. Nested Structures • A structure member can have any data type—including another structure (but not of the same type though). • The inner structure can contain another structure and so on. • C supports nested structures and the following outer structure named student contains an inner structure named dt_birth as one of its four members. 3/10/2021 5.1 Structure and Union 21
  • 23. Initializing a Nested Structure • When it comes to initialization, nested structures resemble multi-dimensional arrays. • For every level of nesting, a set of inner braces have to be used for members of the inner structure. 3/10/2021 5.1 Structure and Union 23
  • 24. Accessing Members • A member of an inner structure is connected by a dot to its immediately enclosing structure, which is connected by another dot to the outer structure. 3/10/2021 5.1 Structure and Union 24
  • 25. Arrays as structure members 3/10/2021 5.1 Structure and Union 25
  • 26. Arrays Of Structures • We used two structure variables, stud1 and stud2, to handle data of two students. • This technique won’t work with 500 students. • C supports an array of structures, whose definition may or may not be combined with the declaration of the structure. • The following statement defines an array of type struct student that can hold 50 sets (or records) of student data. 3/10/2021 5.1 Structure and Union 26
  • 27. Arrays Of Structures • Alternatively, you can separate the declaration and definition. • You can also use typedef to replace struct student with STUDENT. 3/10/2021 5.1 Structure and Union 27
  • 28. Arrays Of Structures 3/10/2021 5.1 Structure and Union 28
  • 29. Structures in functions 3/10/2021 5.1 Structure and Union 29
  • 30. Structures in functions • A function using a structure as argument copies the entire structure. • If the structure contains an array, it too will be copied. • A program may run out of memory when using structures as arguments. • A structure containing numerous members and large arrays can lead to stack overflow and cause the program to abort 3/10/2021 5.1 Structure and Union 30
  • 31. 3/10/2021 5.1 Structure and Union 31
  • 32. 3/10/2021 5.1 Structure and Union 32
  • 33. Bit fields • Have our programs wasted memory? – Yes, in many cases they have. • We used 2-byte short integers to store each component of a date when a few bits would have sufficed. • We also wasted 15 bits of the 16 available in short to set a flag to 0 and 1 3/10/2021 5.1 Structure and Union 33
  • 34. Bit fields • It’s time to know that C supports a memory saving feature—the bit field. • It can be used with the right number of bits, rather than bytes, to store data. • One or two bits are adequate to represent the sex. • while six or seven bits are good enough to represent the age. • Bit fields can be used only as structure members. • Properly sized bit fields prevent both data overflow and memory wastage. 3/10/2021 5.1 Structure and Union 34
  • 35. Example • The first two members, id and age, are bit fields. • The declaration of a bit field specifies an int (signed or unsigned), followed by the member name, a colon and the number of allocated bits. • Here, id and age occupy 10 and 6 bits, respectively. • This means that the maximum values of id and age are restricted to 1023 and 63, respectively. • sizeof evaluates the size of emp to 32. • A similar structure using two short variables for id and age would occupy 34 bytes. 3/10/2021 5.1 Structure and Union 35
  • 36. Unions • When searching a database using a person’s id, you must have often wanted to search by name as well. • That is possible if the two attributes are held in a union, a data type that resembles a structure in form. • A union comprises two or more members that share the same memory, with the most recent assignment to a member being active at any instant. • You can define a union with many members, but only one member can contain a value at any given time. • Unions provide an efficient way of using the same memory location for multiple purposes. • Consider the following declaration and definition of a union 3/10/2021 5.1 Structure and Union 36
  • 37. Unions 3/10/2021 5.1 Structure and Union 37 • A union is declared, defined and accessed exactly like a structure. • The previous statement declares a two-member union named uemp and simultaneously defines the union variable u. • The members are accessed as u.emp_id and u.name. • However, both members share a single memory region and you can correctly access only one member at a time—the one that was last assigned.
  • 39. Unique Attributes of Unions • (1) All members of a union can’t be initialized simultaneously. • (2) The size of a union is determined by the size of the member having the largest footprint in memory. (For uemp, this would be 30, the size of the name field). • (3) The compiler doesn’t output an error when you access a member that was not the last one to be assigned. A programmer must keep track of the member that is active at any instant. • (4) You can use a union to assign a value to a member and read it back using a different member. 3/10/2021 5.1 Structure and Union 39
  • 40. Unions • A union can easily determine whether a machine is little-endian or big-endian. • In a big-endian machine, the most significant bit is stored first while the reverse is true for little-endian machines. • However, unions are mainly used as memory- saving objects. 3/10/2021 5.1 Structure and Union 40
  • 43. Difference between Structure and Union 3/10/2021 5.1 Structure and Union 43
  • 44. The enumerated type (enum) • We have used symbolic constants to represent integers using the #define feature of the preprocessor. • C also supports the user-defined enumeration data type that assigns names to a set of integer values called enumerators. • For instance, you can create a set of named constants using the enum keyword. 3/10/2021 5.1 Structure and Union 44
  • 45. • This statement creates a set of enumerated integer values which, by default, begin with 0. • YES evaluates to 0, while NO and CANT_SAY have the values 1 and 2, respectively. • If this declaration is made before main, you can use NO to represent 1 anywhere in the program. 3/10/2021 5.1 Structure and Union 45
  • 46. • You can now create one or more enum variables of type eday. 3/10/2021 5.1 Structure and Union 46
  • 47. 3/10/2021 5.1 Structure and Union 47
  • 48. Abbreviating a Data Type : The typedef Feature • The typedef keyword is used to abbreviate the names of data types. • Using A Data type LL instead of long long involves less typing. • The syntax of typedef is simple; follow typedef with the existing data type and its proposed synonym. 3/10/2021 5.1 Structure and Union 48
  • 50. Thank you 3/10/2021 5.1 Structure and Union 50