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

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 – ProblemSolving and Programming 3/10/2021 5.1 Structure and Union 2 Syllabus
  • 3.
    Contents • There are4 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 • Coffers 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 • Agroup 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 Defininga 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 Defininga 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
  • 8.
  • 9.
    Accessing Members ofa Structure 3/10/2021 5.1 Structure and Union 9
  • 10.
    Combining Declaration, Definitionand 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 StructureTag • 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.
  • 13.
  • 14.
    Memory Layout ofMembers 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 ofMembers 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.
  • 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 • Astructure 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
  • 22.
  • 23.
    Initializing a NestedStructure • 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 • Amember 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 structuremembers 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/20215.1 Structure and Union 28
  • 29.
    Structures in functions 3/10/20215.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.
  • 32.
  • 33.
    Bit fields • Haveour 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’stime 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 firsttwo 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 searchinga 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 Structureand 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.
  • 38.
  • 39.
    Unique Attributes ofUnions • (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 unioncan 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
  • 41.
  • 42.
  • 43.
    Difference between Structureand 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 statementcreates 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 cannow create one or more enum variables of type eday. 3/10/2021 5.1 Structure and Union 46
  • 47.
  • 48.
    Abbreviating a DataType : 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
  • 49.
  • 50.
    Thank you 3/10/2021 5.1Structure and Union 50