User Defined data type
STRUCTURE
Ms.P.ANANTHI, AP/CSD, KONGU ENGINEERING COLLEGE 1
TOPICS COVERED
oStructure basics
oDeclaring and defining a structure
oAttributes of structure
oNested structures
oArrays as structure members
oArrays of structure
oPassing arrays as arguments to structure
Recall
• What is a datatype?
An attribute associated with a piece of data that tells a
computer system how to interpret its value.
DATA TYPE CLASSIFICATION
Datatypes
Primary
Integer Character Float Double Void
Derived
Functions Array Pointer
User
defined
Structure Union Class Enum typedef
Structure basics
oA structure is a collection of variable under a single name used for
the storage of heterogenous data(data of different datatypes).
oThe individual elements of the structure are known as members
Need for structure
oArrays are used for storing homogenous data.
oBut it is convenient way of grouping together logically related data
items.
STRUCTURE DECLARATION
• A structure object can be referred as instance or structure
variable. A structure declaration consists of,
oThe keyword struct
oStructure tag name
oComma separated list of identifiers
oA terminating semicolon
Syntax
• struct structure_tag_name
{
data_type
member_name1;
data_type member_na
me1;
};
• struct student
{
char name[20];
int rollno;
};
STRUCTURE DECLARATION
struct student //structure name
{
char name[20];
int rollno; // member of
structure
};
struct student s1,s2;// structure
varaible
struct student
{
char name[20];
int rollno;
}s1,s2;
• When we declare variable of the structure, separate memory
is allocated for each variable.
s1 s2
20 bytes 2 byes 20 bytes 2 bytes
22 bytes 22 bytes
Declaring Structure without struct tag
• If declaration and definition are combined the structure tag
can be omitted.
• This is usually done when no more structure variables of that
require to be defined later in the program
Example
struct
{
char name[20];
int rollno;
}student1={"Kanmani",16}, student2={"Kathija",17};
Import attributes of structure
• There are no conflicts between structure templates, their
instantiated variables and members.
• are only operators that can be used on a structure
• A structure can be copied to another structure provided both
objects are based on the same template
= . -> &
• No arithmetic, relational or logical operations can be performed on
structures.
• It is not possible to compare two structures with one operator.
• When a structure is passed by name as an argument to a function,
the entire structure is copied inside the function
• A member of a structure can contain a reference to another
structure of the same type[self-referential structure]
Accessing members of the structure
1.After declaring the structure, the members of the structure can be
accessed by using any of the following three methods.
Using dot operator
Dot operator is also known as direct member access operator or
period operator or member operator. Its access structure member
via structure object name.
Syntax: Structure_object_name.structure_member_name
Using arrow operator
• Arrow operator(->) is also known as indirect member access
operator or period operator or member operator.Its access
structure member via pointer to the structure.
• Syntax: pointer_to_structure->structure_member_name
Using Dereferencing operator
• By using dereferencing operator * and direct memory access
operator. to access the members of the structure.
• Syntax:* pointer_to_structure.structure_member_name
STRUCTURE INITIALIZATION
• The members of the structure object can be initialized by
providing an initialization list which is a comma separated list
of initializer. The members which are explicitly initialized by
the programmer are initialized to the data types's default
value by the system.
• Syntax: Struct structure_tag_name
structure_variable1={initialization list};
Example
struct student
{
char name[20];
int rollno;
};
struct student s1={"Kanmani",16};
struct student s2={"Kathija",17};
Rules for initializing a structure
• We cannot initialize individual members inside the structure
template.
• The order of the values enclosed in braces must match the
order of members in the structure definition
• It is permitted to have partial initialization.
• The uninitialized members will be initialized with default
values
Nested structures
A structure can have
any datatype
including another structure.
struct name_1
{
member1;
member2;
.
.
membern;
struct name_2
{
member_1;
member_2;
.
.
member_n;
}, var1
} var2;
Nested structure Example 1
struct student{
char name[300];
struct{
short day;
short moth;
Short year;
}date_birth;
int roll_no;
int total_marks;
};
struct student stud1;
1. The declaration of inner structure of the
inner structure forms part of
the declaration of the outer one.
2. Separate structure variable cannot be
created for date_birth.
Nested structure Example 1
struct dob{
short day;
short moth;
short year;
};
struct student{
char name[300];
struct dob date_birth;
int roll_no;
int total_marks;
};
struct student stud1;
struct dob dob1;
1. Two structures are created, the
dependent structure dob is used inside
the main structure as a member.
Initializing a nested structure
• It is initialized as like multi-
dimensional arrays.
• For every level of nesting, a
set of inner braces have to
be used for members of the
inner structure.
struct dob{
short day;
short month;
short year;
};
struct student{
char name[300];
struct dob date_birth;
int roll_no;
int total_marks;
};
struct student stud1;
struct dob dob1;
struct stud1={"Ananthi",{01,01,1998},2345,578};
Accessing members of Nested structure
• A member of an inner structure is connected
by a dot to its immediate enclosing structure,
which is connected by another dot to the outer
structure.
outer_structure.inner_structure.member
Example:
Stud1.dob.month;
struct dob{
short day;
short month;
short year;
};
struct student{
char name[300];
struct dob date_birth;
int roll_no;
int total_marks;
};
struct student stud1;
struct dob dob1;
struct stud1={"Ananthi",{01,01,1998},2345,578};
Student.dob.month=06;
Typedef Feature
• The typedef keyword is used to
abbreviate the names of the data
types.
Syntax
typedef data_type new name;
typedef unsigned int UNIT;
UNIT int_var;
typedef unsigned long ulong;
Ulong long_var;
struct student{
char name[50];
int roll_no;
int dt_birth;
};
Typedef struct student
Examinee;
Examinee stud1,stud2;
typedef struct student{
char name[50];
int roll_no;
int dt_birth;
}Examinee;
Examinee stud1,stud2;
Recalling Array
• Arrays are used to store multiple values in a single
variable, instead of declaring separate variables for
each value.
Arrays as structure members
Declaration
• An array can also be a member
of structure
Example
struct student{
char name[50];
int roll_no;
short mark_pc[3];
};
Initialization
• A variable of this type is initialized using
a separate set of braces for the values.
struct student stud1={"Tony
stark",22,{85,97,91}};
• The individual elements of the array can
also be accessed using index.
stud1.mark_pc[0]=90
Example
#include<stdio.h>
struct student
{
char name[20];
int id;
float marks;
};
void main()
{
struct student s1,s2,s3;
int dummy;
printf("Enter the name, id, and marks of student 1 ");
scanf("%s %d %f",s1.name,&s1.id,&s1.marks);
scanf("%c",&dummy);
printf("Enter the name, id, and marks of student 2 ");
scanf("%s %d %f",s2.name,&s2.id,&s2.marks);
scanf("%c",&dummy);
printf("Enter the name, id, and marks of student 3 ");
scanf("%s %d %f",s3.name,&s3.id,&s3.marks);
scanf("%c",&dummy);
printf("Printing the details....n");
printf("%s %d %fn",s1.name,s1.id,s1.marks);
printf("%s %d %fn",s2.name,s2.id,s2.marks);
printf("%s %d %fn",s3.name,s3.id,s3.marks);
}
Arrays as structures
struct student{
char name[300];
int roll_no;
int total_marks;
}stud[50];
Or
typedef struct student{
char name[300];
int roll_no;
int total_marks;
}STUDENT;
STUDENT stud[50];
• It is a collection of structures
• It is used to store multiple entities of
different datatype.
• A collection of multiple structures
variables where each variable
contains information about different
entities
Arrays as Structures
Name
10 bytes
Roll no
4 bytes
Total
marks
4 bytes
Name
10 bytes
Roll no
4 bytes
Total
marks
4 bytes
Stud[0] 18 bytes Stud[1] 18 bytes
struct student{​
char name[10];​
int roll_no;​
int total_marks;​
}stud[50];
Arrays as structures
• The array can be partially or fully initialized
for each array elements by enclosing the
initializers for each array element in a set of
curly braces. Each set is separated by a
comma, while the entire set of initializers are
enclosed by outermost braces.
• Each members of each array element of
the array is accessed by using a dot
to connect the members to the array
element.
STUDENT stud[50]={
{"Kanmani",16,550},
{"Kathija",17,560},
{"Rambo",80,420},
};
Strcpy(stud[4].name,"Vignesh");
stud[4].roll_no=92;
stud[4].total_marks=590;
Structures in Function
A structure related data item can take on the following forms when used as a function arguments,
1. An element of a structure.
The function copies this element which is represented in the form structure.member.
2. The structure name.
The function copies the entire structure. It doesn't interpret the name of the structure as a pointer.
3. A pointer to a structure or a member.
It is used for returning multiple values or avoiding the overhead of copying an entire structure
inside a function.
struct dob{
short day;
short moth;
short year;
};
void display(struct dob d);// Function declaration
void display(struct dob d)// Function definition
{
printf("Date is %hd/%d.%dn",d.day,d.month,d.year);
}
struct dob today={29,12,2004};
display(today);// Function calling
Example
#include <stdio.h>
struct student {
char name[50];
int per,rno;
};
void display(int a, int b);
int main() {
struct student s1;
printf("Enter name: ");
gets(s1.name);
printf("Enter the roll number: ");
scanf("%d",&s1.rno);
printf("Enter percentage: ");
scanf("%d", &s1.per);
display(s1.rno,s1.per);
return 0;
}
void display(int a, int b ) {
printf("nDisplaying informationn");
printf("Roll number: %d", a);
printf("nPercentage: %d", b);
}
Pointers to Structures
• A structure pointer is defined as the pointer
which points to the address of the memory
block that stores a structure .
• A pointer to a structure must be defined
before it is pointed to a structure variable.
struct rectangle{
short length;
short width;
} rect1={10,20};
struct rectangle *p;
p= &rect1;
The structure members can be accessed in
three ways,
rect1.length -- It doesn't involve pointer
(*p).length -- Pointer de-referenced with * and
then connected to the member
p-->length – Uses a special operator -> that
works only with structures
struct rectangle{
short length;
short width;
} rect1={10,20};
struct rectangle *p;
p= &rect1;
Example
// C Program to demonstrate Structure pointer
#include <stdio.h>
#include <string.h>
struct Student {
int roll_no;
char name[30];
char branch[40];
int batch;
};
int main()
{ struct Student s1;
struct Student * ptr = &s1;
s1.roll_no = 27;
strcpy(s1.name, "Kamlesh Joshi");
strcpy(s1.branch, "Computer Science And Engineering");
s1.batch = 2019;
printf("Roll Number: %dn", (*ptr).roll_no);
printf("Name: %sn", (*ptr).name);
printf("Branch: %sn", (*ptr).branch);
printf("Batch: %d", (*ptr).batch);
return 0;
}
Union
• A union comprises of two or more members
that shares the same memory location, with
most recent assignment to a member being
active at any instant.
• It is declared and defined and
accessed exactly like structure.
union emp{
short emp_id;
char name[30];
}emp1,emp2,emp3;
Or
union emp{
short emp_id;
char name[30];
};
union emp emp1,emp2,emp3;
Union
Accessing a union members : Like structures,
we can access the members of a union by dot
operator.
Var1.member1;
Initialization: It is initialized by simply assigning
a value to it.
var1.member1 = some_value;
Note: only one member can contain some
value at a given instance of time.
union un {
int member1;
char member2;
float member3;
};
int main()
{
union un var1;
var1.member1 = 15;
printf("The value stored in member1 = %d",
var1.member1);
return 0;
}
Union Example
#include <stdio.h>
// declaring multiple unions
union test1 {
int x;
int y;
} Test1;
union test2 {
int x;
char y;
} Test2;
union test3 {
int arr[10];
char y;
} Test3;
int main()
{
// finding size using sizeof() operator
int size1 = sizeof(Test1);
int size2 = sizeof(Test2);
int size3 = sizeof(Test3);
printf("Sizeof test1: %dn", size1);
printf("Sizeof test2: %dn", size2);
printf("Sizeof test3: %d", size3);
return 0;
}
Output:
Sizeof test1: 4
Sizeof test2: 4
Sizeof test3: 40
Unique Attributes of Union
• All members of a union can't be initialized simultaneously.
• The size of the union is determined by the size of the member
having the largest size in the memory
• When a member is accessed which does not the last one that
is assigned the compiler will not show error
• It is possible to assign value to a member and read it
back using different member.
How structure is different from union?
In the case of a Structure, there is a specific memory location for every input data member. Thus, it
can store multiple values of the various members.
In the case of a Union, there is an allocation of only one shared memory for all the input data
members. Thus, it stores one value at a time for all of its members.
When to use structure and union ?
Unions are better for cases when two or more members need to share the same memory location.
When working with objects with several properties, structures are often employed, however unions
are advised when working with unknown data types.
BIT FIELD
• To avoid wastage of memory and overflow of data bit fields
can be used.
• Bit fields can only be used as a members of the structure
• It is memory saving feature, which can be used with the right
number of bits, rather than
DECLARTION OF BITFIELDS
struct
{
data_type member_name : width_of_bit-field;
};
EXAMPLE:
struct date
{
// month has value between 0 and 15,
// so 4 bits are sufficient for month variable.
int month : 4;
};
Example
// C program to demonstrate use of Bit-fields
#include <stdio.h>
// Space optimized representation of the date
struct date {
int d : 5;
int m : 4;
int y;
};
int main()
{
printf("Size of date is %lu bytesn",
sizeof(struct date));
struct date dt = { 31, 12, 2014 };
printf("Date is %d/%d/%d", dt.d, dt.m, dt.y);
return 0;
}
• A special unnamed bit field of size 0 is used to force alignment on the next boundary.
• We cannot have pointers to bit field members as they may not start at a byte boundary.
• It is implementation-defined to assign an out-of-range value to a bit field member.
• Array of bit fields is not allowed.
Predict the o/p
#include <stdio.h>
struct test {
unsigned int x; // Unsigned integer member x
unsigned int y : 33;// Bit-field member y with 33 bits
unsigned int z; // Unsigned integer member z
};
int main()
{ printf("%lu", sizeof(struct test));// Print the size of struct test
return 0;
}
Enumerated Type
• Before we used #define to represent integers using symbolic constants.
• A user defined data type enumeration data type can be used to represent a set of integer
values called enumerators by default it begins with zero.
• It is mainly used to assign names to integral constants, the names make a program easy to read
and maintain.
Declaration
enum enum_variable {enumerator1, enumerator2,….enumeratorn};
Eg: enum x{YES,NO,MAYBE};
Enumerated Type
enum x{YES,NO,MAYBE};
YES NO MAYBE
0 1 2
Or
enum enum_variable {enumerator1=value,enumerator2=value,….enumeratorn=value};
Eg: enum State {Working = 1, Failed = 0, Freezed = 0};
enum State {Working = 1, Failed = 0, Freezed = 0};
Working Failed Freezed
1 0 0
• // In both of the below cases, "day" is
• // defined as the variable of type week.
•
• enum week{Mon, Tue, Wed};
• enum week day;
•
• // Or
•
• enum week{Mon, Tue, Wed}day;
Examples
#include<stdio.h>
enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};
int main()
{
enum week day;
day = Wed;
printf("%d",day);
return 0;
}
#include <stdio.h>
enum day {sunday = 1, monday, tuesday = 5,
wednesday, thursday = 10, friday, saturday};
int main()
{
printf("%d %d %d %d %d %d %d", sunday, monday,
tuesday,
wednesday, thursday, friday, saturday);
return 0;
}

User defined data types.pptx

  • 1.
    User Defined datatype STRUCTURE Ms.P.ANANTHI, AP/CSD, KONGU ENGINEERING COLLEGE 1
  • 2.
    TOPICS COVERED oStructure basics oDeclaringand defining a structure oAttributes of structure oNested structures oArrays as structure members oArrays of structure oPassing arrays as arguments to structure
  • 3.
    Recall • What isa datatype? An attribute associated with a piece of data that tells a computer system how to interpret its value.
  • 4.
    DATA TYPE CLASSIFICATION Datatypes Primary IntegerCharacter Float Double Void Derived Functions Array Pointer User defined Structure Union Class Enum typedef
  • 5.
    Structure basics oA structureis a collection of variable under a single name used for the storage of heterogenous data(data of different datatypes). oThe individual elements of the structure are known as members Need for structure oArrays are used for storing homogenous data. oBut it is convenient way of grouping together logically related data items.
  • 6.
    STRUCTURE DECLARATION • Astructure object can be referred as instance or structure variable. A structure declaration consists of, oThe keyword struct oStructure tag name oComma separated list of identifiers oA terminating semicolon
  • 7.
    Syntax • struct structure_tag_name { data_type member_name1; data_typemember_na me1; }; • struct student { char name[20]; int rollno; };
  • 8.
    STRUCTURE DECLARATION struct student//structure name { char name[20]; int rollno; // member of structure }; struct student s1,s2;// structure varaible struct student { char name[20]; int rollno; }s1,s2;
  • 9.
    • When wedeclare variable of the structure, separate memory is allocated for each variable. s1 s2 20 bytes 2 byes 20 bytes 2 bytes 22 bytes 22 bytes
  • 10.
    Declaring Structure withoutstruct tag • If declaration and definition are combined the structure tag can be omitted. • This is usually done when no more structure variables of that require to be defined later in the program
  • 11.
  • 12.
    Import attributes ofstructure • There are no conflicts between structure templates, their instantiated variables and members. • are only operators that can be used on a structure • A structure can be copied to another structure provided both objects are based on the same template = . -> &
  • 13.
    • No arithmetic,relational or logical operations can be performed on structures. • It is not possible to compare two structures with one operator. • When a structure is passed by name as an argument to a function, the entire structure is copied inside the function • A member of a structure can contain a reference to another structure of the same type[self-referential structure]
  • 14.
    Accessing members ofthe structure 1.After declaring the structure, the members of the structure can be accessed by using any of the following three methods. Using dot operator Dot operator is also known as direct member access operator or period operator or member operator. Its access structure member via structure object name. Syntax: Structure_object_name.structure_member_name
  • 15.
    Using arrow operator •Arrow operator(->) is also known as indirect member access operator or period operator or member operator.Its access structure member via pointer to the structure. • Syntax: pointer_to_structure->structure_member_name Using Dereferencing operator • By using dereferencing operator * and direct memory access operator. to access the members of the structure. • Syntax:* pointer_to_structure.structure_member_name
  • 16.
    STRUCTURE INITIALIZATION • Themembers of the structure object can be initialized by providing an initialization list which is a comma separated list of initializer. The members which are explicitly initialized by the programmer are initialized to the data types's default value by the system. • Syntax: Struct structure_tag_name structure_variable1={initialization list};
  • 17.
    Example struct student { char name[20]; introllno; }; struct student s1={"Kanmani",16}; struct student s2={"Kathija",17};
  • 18.
    Rules for initializinga structure • We cannot initialize individual members inside the structure template. • The order of the values enclosed in braces must match the order of members in the structure definition • It is permitted to have partial initialization. • The uninitialized members will be initialized with default values
  • 19.
    Nested structures A structurecan have any datatype including another structure. struct name_1 { member1; member2; . . membern; struct name_2 { member_1; member_2; . . member_n; }, var1 } var2;
  • 20.
    Nested structure Example1 struct student{ char name[300]; struct{ short day; short moth; Short year; }date_birth; int roll_no; int total_marks; }; struct student stud1; 1. The declaration of inner structure of the inner structure forms part of the declaration of the outer one. 2. Separate structure variable cannot be created for date_birth.
  • 21.
    Nested structure Example1 struct dob{ short day; short moth; short year; }; struct student{ char name[300]; struct dob date_birth; int roll_no; int total_marks; }; struct student stud1; struct dob dob1; 1. Two structures are created, the dependent structure dob is used inside the main structure as a member.
  • 22.
    Initializing a nestedstructure • It is initialized as like multi- dimensional arrays. • For every level of nesting, a set of inner braces have to be used for members of the inner structure. struct dob{ short day; short month; short year; }; struct student{ char name[300]; struct dob date_birth; int roll_no; int total_marks; }; struct student stud1; struct dob dob1; struct stud1={"Ananthi",{01,01,1998},2345,578};
  • 23.
    Accessing members ofNested structure • A member of an inner structure is connected by a dot to its immediate enclosing structure, which is connected by another dot to the outer structure. outer_structure.inner_structure.member Example: Stud1.dob.month; struct dob{ short day; short month; short year; }; struct student{ char name[300]; struct dob date_birth; int roll_no; int total_marks; }; struct student stud1; struct dob dob1; struct stud1={"Ananthi",{01,01,1998},2345,578}; Student.dob.month=06;
  • 24.
    Typedef Feature • Thetypedef keyword is used to abbreviate the names of the data types. Syntax typedef data_type new name; typedef unsigned int UNIT; UNIT int_var; typedef unsigned long ulong; Ulong long_var; struct student{ char name[50]; int roll_no; int dt_birth; }; Typedef struct student Examinee; Examinee stud1,stud2; typedef struct student{ char name[50]; int roll_no; int dt_birth; }Examinee; Examinee stud1,stud2;
  • 25.
    Recalling Array • Arraysare used to store multiple values in a single variable, instead of declaring separate variables for each value.
  • 26.
    Arrays as structuremembers Declaration • An array can also be a member of structure Example struct student{ char name[50]; int roll_no; short mark_pc[3]; }; Initialization • A variable of this type is initialized using a separate set of braces for the values. struct student stud1={"Tony stark",22,{85,97,91}}; • The individual elements of the array can also be accessed using index. stud1.mark_pc[0]=90
  • 27.
    Example #include<stdio.h> struct student { char name[20]; intid; float marks; }; void main() { struct student s1,s2,s3; int dummy; printf("Enter the name, id, and marks of student 1 "); scanf("%s %d %f",s1.name,&s1.id,&s1.marks); scanf("%c",&dummy); printf("Enter the name, id, and marks of student 2 "); scanf("%s %d %f",s2.name,&s2.id,&s2.marks); scanf("%c",&dummy); printf("Enter the name, id, and marks of student 3 "); scanf("%s %d %f",s3.name,&s3.id,&s3.marks); scanf("%c",&dummy); printf("Printing the details....n"); printf("%s %d %fn",s1.name,s1.id,s1.marks); printf("%s %d %fn",s2.name,s2.id,s2.marks); printf("%s %d %fn",s3.name,s3.id,s3.marks); }
  • 28.
    Arrays as structures structstudent{ char name[300]; int roll_no; int total_marks; }stud[50]; Or typedef struct student{ char name[300]; int roll_no; int total_marks; }STUDENT; STUDENT stud[50]; • It is a collection of structures • It is used to store multiple entities of different datatype. • A collection of multiple structures variables where each variable contains information about different entities
  • 29.
    Arrays as Structures Name 10bytes Roll no 4 bytes Total marks 4 bytes Name 10 bytes Roll no 4 bytes Total marks 4 bytes Stud[0] 18 bytes Stud[1] 18 bytes struct student{​ char name[10];​ int roll_no;​ int total_marks;​ }stud[50];
  • 30.
    Arrays as structures •The array can be partially or fully initialized for each array elements by enclosing the initializers for each array element in a set of curly braces. Each set is separated by a comma, while the entire set of initializers are enclosed by outermost braces. • Each members of each array element of the array is accessed by using a dot to connect the members to the array element. STUDENT stud[50]={ {"Kanmani",16,550}, {"Kathija",17,560}, {"Rambo",80,420}, }; Strcpy(stud[4].name,"Vignesh"); stud[4].roll_no=92; stud[4].total_marks=590;
  • 31.
    Structures in Function Astructure related data item can take on the following forms when used as a function arguments, 1. An element of a structure. The function copies this element which is represented in the form structure.member. 2. The structure name. The function copies the entire structure. It doesn't interpret the name of the structure as a pointer. 3. A pointer to a structure or a member. It is used for returning multiple values or avoiding the overhead of copying an entire structure inside a function.
  • 32.
    struct dob{ short day; shortmoth; short year; }; void display(struct dob d);// Function declaration void display(struct dob d)// Function definition { printf("Date is %hd/%d.%dn",d.day,d.month,d.year); } struct dob today={29,12,2004}; display(today);// Function calling
  • 33.
    Example #include <stdio.h> struct student{ char name[50]; int per,rno; }; void display(int a, int b); int main() { struct student s1; printf("Enter name: "); gets(s1.name); printf("Enter the roll number: "); scanf("%d",&s1.rno); printf("Enter percentage: "); scanf("%d", &s1.per); display(s1.rno,s1.per); return 0; } void display(int a, int b ) { printf("nDisplaying informationn"); printf("Roll number: %d", a); printf("nPercentage: %d", b); }
  • 34.
    Pointers to Structures •A structure pointer is defined as the pointer which points to the address of the memory block that stores a structure . • A pointer to a structure must be defined before it is pointed to a structure variable. struct rectangle{ short length; short width; } rect1={10,20}; struct rectangle *p; p= &rect1;
  • 35.
    The structure memberscan be accessed in three ways, rect1.length -- It doesn't involve pointer (*p).length -- Pointer de-referenced with * and then connected to the member p-->length – Uses a special operator -> that works only with structures struct rectangle{ short length; short width; } rect1={10,20}; struct rectangle *p; p= &rect1;
  • 36.
    Example // C Programto demonstrate Structure pointer #include <stdio.h> #include <string.h> struct Student { int roll_no; char name[30]; char branch[40]; int batch; }; int main() { struct Student s1; struct Student * ptr = &s1; s1.roll_no = 27; strcpy(s1.name, "Kamlesh Joshi"); strcpy(s1.branch, "Computer Science And Engineering"); s1.batch = 2019; printf("Roll Number: %dn", (*ptr).roll_no); printf("Name: %sn", (*ptr).name); printf("Branch: %sn", (*ptr).branch); printf("Batch: %d", (*ptr).batch); return 0; }
  • 37.
    Union • A unioncomprises of two or more members that shares the same memory location, with most recent assignment to a member being active at any instant. • It is declared and defined and accessed exactly like structure. union emp{ short emp_id; char name[30]; }emp1,emp2,emp3; Or union emp{ short emp_id; char name[30]; }; union emp emp1,emp2,emp3;
  • 38.
    Union Accessing a unionmembers : Like structures, we can access the members of a union by dot operator. Var1.member1; Initialization: It is initialized by simply assigning a value to it. var1.member1 = some_value; Note: only one member can contain some value at a given instance of time. union un { int member1; char member2; float member3; }; int main() { union un var1; var1.member1 = 15; printf("The value stored in member1 = %d", var1.member1); return 0; }
  • 39.
    Union Example #include <stdio.h> //declaring multiple unions union test1 { int x; int y; } Test1; union test2 { int x; char y; } Test2; union test3 { int arr[10]; char y; } Test3; int main() { // finding size using sizeof() operator int size1 = sizeof(Test1); int size2 = sizeof(Test2); int size3 = sizeof(Test3); printf("Sizeof test1: %dn", size1); printf("Sizeof test2: %dn", size2); printf("Sizeof test3: %d", size3); return 0; } Output: Sizeof test1: 4 Sizeof test2: 4 Sizeof test3: 40
  • 40.
    Unique Attributes ofUnion • All members of a union can't be initialized simultaneously. • The size of the union is determined by the size of the member having the largest size in the memory • When a member is accessed which does not the last one that is assigned the compiler will not show error • It is possible to assign value to a member and read it back using different member.
  • 41.
    How structure isdifferent from union? In the case of a Structure, there is a specific memory location for every input data member. Thus, it can store multiple values of the various members. In the case of a Union, there is an allocation of only one shared memory for all the input data members. Thus, it stores one value at a time for all of its members. When to use structure and union ? Unions are better for cases when two or more members need to share the same memory location. When working with objects with several properties, structures are often employed, however unions are advised when working with unknown data types.
  • 42.
    BIT FIELD • Toavoid wastage of memory and overflow of data bit fields can be used. • Bit fields can only be used as a members of the structure • It is memory saving feature, which can be used with the right number of bits, rather than
  • 43.
    DECLARTION OF BITFIELDS struct { data_typemember_name : width_of_bit-field; }; EXAMPLE: struct date { // month has value between 0 and 15, // so 4 bits are sufficient for month variable. int month : 4; };
  • 44.
    Example // C programto demonstrate use of Bit-fields #include <stdio.h> // Space optimized representation of the date struct date { int d : 5; int m : 4; int y; }; int main() { printf("Size of date is %lu bytesn", sizeof(struct date)); struct date dt = { 31, 12, 2014 }; printf("Date is %d/%d/%d", dt.d, dt.m, dt.y); return 0; }
  • 45.
    • A specialunnamed bit field of size 0 is used to force alignment on the next boundary. • We cannot have pointers to bit field members as they may not start at a byte boundary. • It is implementation-defined to assign an out-of-range value to a bit field member. • Array of bit fields is not allowed.
  • 46.
    Predict the o/p #include<stdio.h> struct test { unsigned int x; // Unsigned integer member x unsigned int y : 33;// Bit-field member y with 33 bits unsigned int z; // Unsigned integer member z }; int main() { printf("%lu", sizeof(struct test));// Print the size of struct test return 0; }
  • 47.
    Enumerated Type • Beforewe used #define to represent integers using symbolic constants. • A user defined data type enumeration data type can be used to represent a set of integer values called enumerators by default it begins with zero. • It is mainly used to assign names to integral constants, the names make a program easy to read and maintain. Declaration enum enum_variable {enumerator1, enumerator2,….enumeratorn}; Eg: enum x{YES,NO,MAYBE};
  • 48.
    Enumerated Type enum x{YES,NO,MAYBE}; YESNO MAYBE 0 1 2 Or enum enum_variable {enumerator1=value,enumerator2=value,….enumeratorn=value}; Eg: enum State {Working = 1, Failed = 0, Freezed = 0}; enum State {Working = 1, Failed = 0, Freezed = 0}; Working Failed Freezed 1 0 0
  • 49.
    • // Inboth of the below cases, "day" is • // defined as the variable of type week. • • enum week{Mon, Tue, Wed}; • enum week day; • • // Or • • enum week{Mon, Tue, Wed}day;
  • 50.
    Examples #include<stdio.h> enum week{Mon, Tue,Wed, Thur, Fri, Sat, Sun}; int main() { enum week day; day = Wed; printf("%d",day); return 0; } #include <stdio.h> enum day {sunday = 1, monday, tuesday = 5, wednesday, thursday = 10, friday, saturday}; int main() { printf("%d %d %d %d %d %d %d", sunday, monday, tuesday, wednesday, thursday, friday, saturday); return 0; }