0% found this document useful (0 votes)
13 views

Unit IV Part A - User Defined Data Types

The document discusses user defined data types in C, specifically structures, unions, enumerations, and bit-fields. It defines structures as a heterogeneous, linear, and static data structure made up of members that can be different data types. Structures are useful for managing related data items. The document provides details on defining structures, declaring structure variables, and processing structures, including nested structures and arrays of structures.

Uploaded by

Technical Bhat
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Unit IV Part A - User Defined Data Types

The document discusses user defined data types in C, specifically structures, unions, enumerations, and bit-fields. It defines structures as a heterogeneous, linear, and static data structure made up of members that can be different data types. Structures are useful for managing related data items. The document provides details on defining structures, declaring structure variables, and processing structures, including nested structures and arrays of structures.

Uploaded by

Technical Bhat
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

11/01/17

USER DEFINED DATA TYPES


STRUCTURES, UNIONS, ENUMERATIONS AND BIT-FIELDS

DR. M TARIQ BANDAY


UNIVERSITY OF KASHMIR

Lecture Notes
Dr. M Tariq Banday, University of Kashmir, Srinagar

Dr. M Tariq Banday


University of Kashmir, Srinagar
www.banday.in
USER DEFINED DATA TYPES

www.banday.in
• DATA IS STORED IN COMPUTER MEMORY USING VARIOUS REPRESENTATIONS.
DATA TYPES ARE VARIOUS SUCH METHODS.
• EACH DATA TYPE IS REPRESENTED IN MEMORY DIFFERENTLY AND DIFFERENT
OPERATIONS ARE ALLOWED UPON EACH.
• DATA TYPES CAN BE CLASSIFIED INTO TWO BROADER CATEGORIES NAMELY IN-
BUILT AND USER DEFINED DATA TYPES.
• IN-BUILT DATA TYPES ARE THOSE WHICH ARE DEFINED BY C COMPILER AND AS
www.banday.in

SUCH VARIABLES OF SUCH TYPES CAN BE READILY CREATED.


• USER DEFINED DATA TYPES ARE TO BE DEFINED BY THE PROGRAMMER BEFORE
DECLARING VARIABLES OF SUCH TYPE. SUCH DATA TYPES ARE CALLED DATA
STRUCTURES.
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in

1
11/01/17

www.banday.in
USER DEFINED DATA TYPES

www.banday.in
• USER DEFINED DATA TYPES ARE CALLED DATA STRUCTURES (A LOGICAL METHOD
OF REPRESENTING DATA IN COMPUTER MEMORY).
• USER DEFINED DATA TYPES INCLUDE ARRAYS, STRUCTURES, UNIONS,
ENUMERATIONS, LINKED LISTS, STACKS, QUEUES, TREES, AND OTHERS.
• THIS PRESENTATION DISCUSSES
• STRUCTURES,
• UNIONS,
• ENUMERATIONS AND
www.banday.in

• BIT-FIELDS.
• OTHER DATA TYPES ARE COVERED IN DATA STRUCTURES TOPIC.

Lecture Notes
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in

Dr. M Tariq Banday


University of Kashmir, Srinagar
www.banday.in

www.banday.in

STRUCTURES
www.banday.in

Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in

2
11/01/17

www.banday.in
USER DEFINED DATA TYPES - STRUCTURES

www.banday.in
• A STRUCTURES IS A HETEROGENEOUS, LINEAR AND STATIC DATA
STRUCTURE. IT IS OFTEN CALLED A RECORD.
• A STRUCTURE IS A DATA STRUCTURE IN WHICH EACH ITEM IS
IDENTIFIED BY ITS OWN IDENTIFIER EACH OF WHICH IS KNOWN AS A
MEMBER OF THE STRUCTURE.
• A MEMBER OF THE STRUCTURE MAY BE AN INBUILT DATA TYPE OR A
USER DEFINED DATA TYPE.
www.banday.in

• IN CASE A STRUCTURE INCLUDES A MEMBER WHICH IS A POINTER OF


THE SAME USER DEFINED DATA TYPE (STRUCTURE), THEN IT IS CALLED

Lecture Notes
A LINKED LIST OR SELF REFERENTIAL STRUCTURE.
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in

Dr. M Tariq Banday


University of Kashmir, Srinagar
www.banday.in
USER DEFINED DATA TYPES - STRUCTURES

www.banday.in
• IN CASE A STRUCTURE INCLUDES A MEMBER WHICH IS A POINTER OF THE
SAME USER DEFINED DATA TYPE (STRUCTURE), THEN IT IS CALLED A LINKED
LIST OR SELF REFERENTIAL STRUCTURE.
• A STRUCTURE IS USEFUL IN PROGRAMS WHERE VARIOUS INDIVIDUAL DATA
ITEMS OF DIFFERENT DATA TYPES EXIST AND HAVE RELATIONSHIP WITH
EACH OTHER.
• STRUCTURES HELP IN MANAGING VARIOUS DATA ITEMS WHICH ARE
www.banday.in

RELATED TO ONE ANOTHER AND YET ARE OF DIFFERENT DATA TYPES.


• A STRUCTURE IS USUALLY CREATED FOR AN ENTITY WHICH HAS SEVERAL
ATTRIBUTES. EACH ATTRIBUTE IS REPRESENTED BY A MEMBER OF THE
STRUCTURE.
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in

3
11/01/17

www.banday.in
USER DEFINED DATA TYPES - STRUCTURES

www.banday.in
• LEARNING STRUCTURES
• STRUCTURE DEFINITION
• STRUCTURE VARIABLE DECELERATIONS
• PROCESSING STRUCTURE VARIABLES
• NESTED STRUCTURES AND THEIR PROCESSING
• ARRAY OF STRUCTURES
• POINTERS AS STRUCTURE MEMBERS
www.banday.in

• TYPEDEF
• POINTER TO STRUCTURE
• PASSING STRUCTURES TO FUNCTIONS

Lecture Notes
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in

Dr. M Tariq Banday


University of Kashmir, Srinagar
www.banday.in
USER DEFINED DATA TYPES - STRUCTURES

www.banday.in
• STRUCTURE DEFINITION
• IN ORDER TO MAKE USE OF STRUCTURES, IT IS NECESSARY TO FIRST DEFINE THE
COMPOSITION OF STRUCTURE. THIS DEFINITION SERVES AS A TEMPLATE FOR FUTURE
DECELERATION OF VARIABLES. THE STRUCTURE DEFINITION DOES NOT RESERVE OR ALLOCATE
ANY MEMORY AT ALL.
• SYNTAX:
struct TAG {
MEMBER 1;
www.banday.in

MEMBER 2;
……….
MEMBER N;
};

Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in

4
11/01/17

www.banday.in
USER DEFINED DATA TYPES - STRUCTURES

www.banday.in
struct TAG {
1. Is the required keyword for defining a structure.
1 2 MEMBER 1;
2. Is the name of the structure being defined. It is an
MEMBER 2;
3 identifier used to identify the structure and must
……….
confer to all naming rules and conventions set for
MEMBER N;
the identifiers.
};

3. Is the list of members enclosed within curly braces and terminated with a
terminator. Each of these members is a deceleration statement without any
initialization. These members may include inbuilt or user defined data types.
www.banday.in

Initialization of the members within structures is not permitted because a structure


definition is only a template and no actual memory is released at this point.
However, initialization is permissible at the time of declaring structure variable.
Further, a storage class specifier cannot be specified with the deceleration of the

Lecture Notes
member. It can be specified at the time of structure variable deceleration.
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in

Dr. M Tariq Banday


University of Kashmir, Srinagar
www.banday.in
USER DEFINED DATA TYPES - STRUCTURES

www.banday.in
Example – Structure Definition
struct BOOK{
char Title [20]; In this example a structure namely BOOK having
char Author [20]; members namely Title, Author, Edition and Price is
int Edition; defined.
float Price;
};

struct DATE{ In this example a structure named DATE having


www.banday.in

unsigned int Day; members namely Title, Author, Edition and Price
unsigned int Month; is defined.
unsigned int Year;
};

Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in

5
11/01/17

www.banday.in
USER DEFINED DATA TYPES - STRUCTURES

www.banday.in
• STRUCTURE VARIABLE DECELERATION
• IT IS A METHOD OF ASSOCIATING A VARIABLE OR A GROUP OF VARIABLES WITH A SPECIFIED
STRUCTURE TYPE. THE STRUCTURE MUST HAVE BEEN DEFINED PRIOR TO THIS AND MUST HAVE THE
SCOPE.
• SYNTAX:
storageclass struct structurename Var1[={values}], …. VarN[={values}];
1 2 3 4 5 6 7 8
1. Is the storage class spefier, which specifies where and how memory will be reserved for the variable(s). This is
optional.
2. Is the required keyword and must exist for all structure variable decelerations unless typedef statement is used.
3. Is the name of the structure that has already been defined. It may also be stated in the data type of the variables
www.banday.in

that are being declared.


4. Is the name of the structure variable being declared. The name must confer to the naming rules of the identifier.
5. Is optional. Initial set of values enclosed in curly brackets and are to be assigned to the members of the structure
variable. The data type of these variables must match the data type of the corresponding members of the
structure.
6. Is optional and is used to seprate individual structure variables being defined in a single deceleration statement.

Lecture Notes
7. Is optional and similar to 4 and 5.
8. Is the required terminator.
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in

Dr. M Tariq Banday


University of Kashmir, Srinagar
www.banday.in
USER DEFINED DATA TYPES - STRUCTURES

www.banday.in
Example – Structure Variable Deceleration
struct BOOK {
char Title [20]; struct BOOK BI;
char Author [20]; struct BOOK B2={“C Programming Lab”, “M T
int Edition; Banday”, 2015, 320.50};
float Price;
};

struct DATE {
www.banday.in

unsigned int Day;


unsigned int Month; struct DATE DOB, CD={10, 10, 2016};
unsigned int Year;
};

Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in

6
11/01/17

www.banday.in
USER DEFINED DATA TYPES - STRUCTURES

www.banday.in
Example – Structure Variable Deceleration
struct DATE { A structure DATE is defined and two variables of this
unsigned int Day; structure namely DOB and CD are declared. The
individual members of the variable CD are initialized in
unsigned int Month;
the deceleration while as those of DOB remain
unsigned int Year; uninitialized.
}; The memory allocation for the deceleration assuming 2
bytes per unsigned int variable is 6 bytes for each
struct DATE DOB, CD={10, 10, 2016}; variable.

DOB CD
www.banday.in

Day Month Year Day Month Year


10 10 2016
0A00 0A02 0A04 0E00 0E02 0E04
6 Bytes 6 Bytes

Lecture Notes
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in

Dr. M Tariq Banday


University of Kashmir, Srinagar
www.banday.in
USER DEFINED DATA TYPES - STRUCTURES

www.banday.in
Example – Structure Variable Deceleration
struct STUDENT{ The deceleration declares and initializes two structure
int RollNo; variables S1 and S2 of type STUDENT. One member is an
char Name[10]; integer and the other is an array and as such the
deceleration uses strings as the second member.
};

struct STUDENT S1={10, “Bilal”}, S2={11, “Andrew”};

S1
RollNo Name
www.banday.in

0A00 0A02
12 Bytes

Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in

7
11/01/17

www.banday.in
USER DEFINED DATA TYPES - STRUCTURES

www.banday.in
Combining Definition with the Deceleration
It is possible to combine the structure definition and structure variable deceleration in a single statement.
In such a case the name of structure is optional. However, if the structure name is not specified with such
combined structure definition and structure variable deceleration, it is not possible to declare the
variable of the same structure later in the program. The following examples illustrate such

struct DATE { struct STUDENT {


unsigned int Day; int RollNo;
unsigned int Month; char Name[10];
unsigned int Year; } S1={10,”Bilal”}, S2={11, “Andrew”};
} DOB, CD={10, 10, 2016};
www.banday.in

struct { struct {
unsigned int Day; int RollNo;
unsigned int Month; char Name[10];
unsigned int Year; } S1={10,”Bilal”}, S2={11, “Andrew”};

Lecture Notes
} DOB, CD={10, 10, 2016};
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in

Dr. M Tariq Banday


University of Kashmir, Srinagar
www.banday.in
USER DEFINED DATA TYPES - STRUCTURES

www.banday.in
Example – Structure Variable Deceleration
struct STUDENT{ The deceleration declares and initializes two structure
int RollNo; variables S1 and S2 of type STUDENT. One member is an
char Name[10]; integer and the other is an array and as such the
deceleration uses strings as the second member.
};

struct STUDENT S1={10, “Bilal”}, S2={11, “Andrew”};

S1
RollNo Name
www.banday.in

0A00 0A02
12 Bytes

Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in

8
11/01/17

www.banday.in
USER DEFINED DATA TYPES - STRUCTURES

www.banday.in
• PROCESSING STRUCTURE VARIABLES
• MOST OF THE OPERATIONS INVOLVING STRUCTURE VARIABLE PROCESSING REQUIRE
INDIVIDUAL MEMBERS OF THE STRUCTURE TO BE PROCESSED AS SEPARATELY.
• THUS AN INDIVIDUAL STRUCTURE MEMBERS CAN BE ACCESSED BY USING A DOT OPERATOR
CALLED PERIOD.
• IT BELONGS TO THE HIGHEST OPERATOR PRECEDENCE GROUP AND HAS AN LEFT TO RIGHT
PRECEDENCE.
• IT IS ACCESSED IN THE FOLLOWING MANNER:
• structurevariable.member
www.banday.in

• SINCE THE . OPERATOR BELONGS TO THE HIGHEST PRECEDENCE GROUP AND HAS LEFT TO
RIGHT PRECEDENCE, TWO EXPRESSIONS LIKE ++structurevariable.member AND
++(structurevariable.member) ARE EQUIVALENT OR THE EXPRESSIONS

Lecture Notes
&structurevariable.member AND &(++structurevariable.member) ARE EQUIVALENT.
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in

Dr. M Tariq Banday


University of Kashmir, Srinagar
www.banday.in
USER DEFINED DATA TYPES - STRUCTURES

www.banday.in
CD
• PROCESSING STRUCTURE VARIABLES - EXAMPLES
Day Month Year
struct DATE { 10 10 2016
DOB
unsigned int Day; 0E00 0E02 0E04
Day Month Year
unsigned int Month; 6 Bytes
unsigned int Year;
0A00 0A02 0A04
};
6 Bytes
struct date DOB, CD={10,10,2016};

Expressions Results EXPRESSION RESULT


CD.Day 10 DOB.Day=30 WILL STORE 30 IN M.L. 0A00 IDENTIFIED BT DOB.Day
www.banday.in

CD.Month 10 DOB.Month=9 WILL STORE 9 IN M.L. 0A02 IDENTIFIED BT DOB.Month


CD.Year 2016 CD==DOB WILL THROUGH A COMPILER TIME ERROR ILLELEGEL STRUCTURE OPERATION

&CD.Day 0E00 CD=DOB WILL MAKE A MEMBER WISE ASSIGNMENT


&CD.Month 0E02 CD.Day=DOB.Day WILL MAKE ASSIGNMENT OF MEMBER
&(Cd.Month) 0E02
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in

9
11/01/17

www.banday.in
USER DEFINED DATA TYPES - STRUCTURES

www.banday.in
• PROCESSING STRUCTURE VARIABLES - EXAMPLES
struct STUDENT {
int RollNo;
char Name[10];
};
struct STUDENT S2, S1={10,”Bilal”};

Expressions Results Expressions Results


S1.RollNo 10
&S1.RollNo ?
www.banday.in

S1.Name ?
& S1.Name ?
strcpy(S2.Name,”Andrew”); ?
S2.Name[0] ?

Lecture Notes
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in

Dr. M Tariq Banday


University of Kashmir, Srinagar
www.banday.in
USER DEFINED DATA TYPES - STRUCTURES

www.banday.in
Processing Structure Variables – Example
struct student { scanf(“%d”,&s2.p1);
int rollno; printf(“\paper 2 marks: ”);
char fname[10]; scanf(“%d”,&s2.p2);
int p1, p2, total; s2.total = s2.p1 + s2.p2;
}; if(s1.total>s2.total)
main() printf(“\n %s topps %s by %d marks”, s1.name,
{ s2.name, s1.total-s2.total);
struct student s1={1, “bilal”,80, 85, 165}; else if(s2.total>s1.total)
struct student s2; printf(“\n %s topps %s by %d marks”, s2.name,
www.banday.in

printf(“\nroll no : ”); s1.name, s2.total-s1.total);


scanf(“%d”,&s2.rollno); else
printf(“\nname : “); printf(“\n %s and %s have secure same marks %d”,
gets(name); s1.name, s2.name, s1.total);
fflush(stdin); getch();
printf(“\paper 1 marks: ”); }
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in

10
11/01/17

www.banday.in
USER DEFINED DATA TYPES – NESTED STRUCTURES

www.banday.in
• STRUCTURE DEFINITIONS CAN BE NESTED IN OTHER
STRUCTURE DEFINITIONS CALLED NESTED STRUCTURES.
• INNER STRUCTURE DEFINITION
• THE STRUCTURE DEFNED WITHIN OTHER STRUCTURE DEFINITION
• OUTER STRUCTURE DEFINITION
• STRUCTURE DEFINITION CONTAINING OTHER STRUCTURE
www.banday.in

DEFINITIONS
• THE NAME OF THE INNER STRUCTURE DEFINITION IS
OPTIONAL.

Lecture Notes
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in

Dr. M Tariq Banday


University of Kashmir, Srinagar
www.banday.in
USER DEFINED DATA TYPES – NESTED STRUCTURES

www.banday.in
example in this definition student is outer structure and dob
struct student { and marks are inner structure definitions which are
int rollno; nested inside the student structure.
char fname[10]; • decelerations and initilizations
int day, month, year; • struct student s1;
int marksp1, marksp2, marksp3;
};
• struct student s2 = {10, “bilal”, {1,1,1995},
The same structure could be more managebly
{80,80,90}};
defined as:
struct student {
• accessing members
www.banday.in

int rollno;
outerstructurevariable.innserstructurevariable.member
char fname[10];
e.g.
struct { int day, month, year; } dob;
s1.marks.marksp2 = 50; will assign 80 to marks of paper2
struct { int marksp1, marksp2, marksp3;}
of student s1.
marks; s2. dob.day will return 10. i.e. the day of birth of student
}; s1
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in

11
11/01/17

USER DEFINED DATA TYPES – NESTED STRUCTURES


• IT IS ALSO POSSIBLE TO HAVE MORE THAT ONE VARIABLE OF THE INNER STRUCTURES IN AN OUTER
STRUCTURE AS SHOWN IN THE FOLLOWING EXAMPLE:
struct student {
int rollno;
char fname[10];
struct date {int day, month, year;} dob, doa;
Struct marks{int marksp1, marksp2;} theory, prac;
};

• EXAMPLE USES
• student s1 = {11, “bilal”, {10,10,1980}, {1,1,2015}, {50,48}, {25,34}};
• student s2;
• s2.rollno=22;
• strcpy(s2.fname,”amin”);
• s2.dob.day=15
• s2.doa.year=2015;

Lecture Notes
• s2.theory.marksp1=67;
Dr. M Tariq Banday, University of Kashmir, Srinagar

Dr. M Tariq Banday


University of Kashmir, Srinagar
USER DEFINED DATA TYPES – NESTED STRUCTURES
• IT IS ALSO POSSIBLE TO DEFINE THE STRUCTURES DATE AND MARKS OUTSIDE THE STRUCTURE STUDENT AND
THEN DECLARE THE VARIABLES OF TYPE DATE AND MARKS IN THE DEFINITION OF THE STRUCTURE STUDENT.
struct date {
int day;
int month;
int year;
};
struct marks {
int marksp1;
int marksp2;
};
struct student {
int rollno;
char fname[10];
struct date dob, doa;
Struct marks theory, prac;
};
Dr. M Tariq Banday, University of Kashmir, Srinagar

12
11/01/17

USER DEFINED DATA TYPES – NESTED STRUCTURES


• PROCESSING OF NESTED STRUCTURES
• The processing of members of a nested structure which is nested inside other structure needs the use of a
period operator (.) and the number of (.) operators depends upon the levels of nesting.
• E.g. TEST
struct OS { The individual fundamental XS
int W; members W, X, Y and Z can be YS
struct { accessed by expressions: ZS
int X; W X Y Z
struct { TEST.W
Int Y; TEST.XS.X
TEST.XS.YS.Y 0F00 0F03 0F05 0F07
struct {
Int Z;
TEST.XS.YS.ZS.Z 8 Bytes
}ZS;
} YS;
} XS;
Question:
};
Assign1, 2, 3 and 4 to individual fundamental members namely W, X, Y and Z.
struct OS TEST;

Lecture Notes
Dr. M Tariq Banday, University of Kashmir, Srinagar

Dr. M Tariq Banday


University of Kashmir, Srinagar
USER DEFINED DATA TYPES – NESTED STRUCTURES
• PROCESSING OF NESTED STRUCTURES Struct marks TH, PR;
struct date { };
void main(){
int day;
struct student S;
int month;
struct date CD={11,11,2015}; Age;
int year; clrscr();
}; printf(“\nRoll No: “); scanf(“%d”, &S.rollno);
struct marks { printf(“\Nameo: “); scanf(“%s”, S.name);
printf(“\nBirth Date: “); scanf(“%d/%d/%d”,
int marksp1;
&S.DOB.day, &S.DOB.month, &S.DOB.year);
int marksp2;
Age.day=S.DOB.dayCD.day;
}; Age.month=S.DOB.dayCD.month;
struct student { Age.year=S.DOB.dayCD.year;
int rollno; If(Age.day<0) {Age.day+=30;Age.month -=1;}
char fname[10]; If(Age.month<0) {Age.month+=12;Age.year -=1;}
struct date DOB; If(Age.year<0) {printf(“Invalid DOB”);}

Dr. M Tariq Banday, University of Kashmir, Srinagar

13
11/01/17

USER DEFINED DATA TYPES – NESTED STRUCTURES


• PROCESSING OF NESTED STRUCTURES printf(“\nAge: %d days %d Month and
(CONT) %d Years”, Age.DOB.day,
printf(“\nTheory Marks (Paper 1) : “; Age.DOB.month, Age.DOB.year );
scanf(“%d”, &S.TH.marksp1); printf(“\nTheory Marks: %d + %d = %d”,
printf(“\nTheory Marks (Paper 2) : “; S.TH.marksp1, S.TH.marksp2,
S.TH.marksp1+ S.TH.ma);
scanf(“%d”, &S.TH.marksp2);
printf(“\nPractical Marks: %d + %d =
%d”, S.PR.marksp1, S.PR.marksp2,
printf(“\nDetails of Student are: “);
S.PR.marksp1+ S.PR.marksp2);
printf(“\nRoll No: %d”, S.rollno);
}
printf(“\nName: %s”, S.name);
printf(“\nDate of Birth: %d/%d/%d”,

Lecture Notes
S.DOB.day, S.DOB.month, S.DOB.year );
Dr. M Tariq Banday, University of Kashmir, Srinagar

Dr. M Tariq Banday


University of Kashmir, Srinagar
USER DEFINED DATA TYPES – ARRAY OF STRUCTURES
• AN ARRAY IS A LOGICAL DATA STRUCTURE CONSISTING OF A CONTIGUOUS AREA
IN MEMORY CONTAINING FINITE ORDERED SET OF HOMOGENEOUS ELEMENTS. AN
ARRAY AS SUCH MAY CONSIST OF CHARACTERS, INTEGERS, FLOATS, DOUBLES,
ARRAYS, POINTERS OR STRUCTURES.
• THUS AN ARRAY OF STRUCTURES IS A FINITE, HOMOGENEOUS AND LINEAR DATA
STRUCTURE IN WHICH EACH ELEMENT IS A STRUCTURE.
• IT IS OFTEN REQUIRED TO PASS MULTIPLE DATA ITEMS OF SAME TYPE SUCH AS A LIST
OF STUDENTS RECORD. IN SUCH CASE IT IS CONVENIENT TO DEFINE A STRUCTURE
DESCRIBING THE USER DEFINED DATA TYPE AND CREATING AN ARRAY OF
STRUCTURES.
• IT IS CONVENIENT TO USE AN ARRAY INSTEAD OF INDIVIDUAL VARIABLES. BESIDES, IT
ALSO REDUCES THE PROGRAM CODE AND COMPLEXITY.

Dr. M Tariq Banday, University of Kashmir, Srinagar

14
11/01/17

USER DEFINED DATA TYPES – ARRAY OF STRUCTURES


struct book{ MaxI = MinI=0;
char title [20]; for(i=1;i<10;i++) {
char author[20]; If(mybooks[MaxI].cost< mybooks[i].cost) MaxI=i;
If(mybooks[MinI].cost> mybooks[i].cost) MinI=i;}
int pages;
printf(“\nThe Details of the Book having highest
int cost; cost are : “);
}; printf(“\nTitle: %s“, mybooks[MaxI].title);
void main() { printf(“\nAuthor %s : “, mybooks[MaxI].author);
struct book, mybooks[10]; printf(“\nPages %d : “, mybooks[MaxI].Pages);
int I, MaxI, MinI; printf(“\nCost %d: “, mybooks[MaxI].cost);
for(i=0;i<10;i++) printf(“\nThe Details of the Book having lowest cost
{ printf(“\nTitle: “); gets(mybooks[i].title); are : “);
printf(“\nAuthor: “); gets(mybooks[i].author); printf(“\nTitle: %s“, mybooks[MinI].title);
printf(“\nPages: “); printf(“\nAuthor %s : “, mybooks[MinI].author);
scanf(“%d”,mybooks[i].pages); printf(“\nPages %d : “, mybooks[MinI].Pages);
printf(“\nCost: “); scanf(“%d”,mybooks[i].cost); printf(“\nCost %d: “, mybooks[MinI].cost);

Lecture Notes
} }
Dr. M Tariq Banday, University of Kashmir, Srinagar

Dr. M Tariq Banday


University of Kashmir, Srinagar
USER DEFINED DATA TYPES – STRUCTURES & POINTERS
• A POINTER IS A REFERENCE TO SOME OBJECT. THE OBJECT MAY BE INBUILT
OBJECT OR USER DEFINED OBJECT (LIKE STRUCTURE) OR A FUNCTION OR A
REFERENCE TO SOME OTHER OBJECT.
• IN CASE THE OBJECT IS A STRUCTURE, IT IS THEN CALLED POINTER TO
STRUCTURE.
• IN ORDER TO USE A POINTER TO A STRUCTURE MUST BE DEFINED FIRST.
• A POINTER TO A STRUCTURE VARIABLE MAY BE DECLARED IN A MANNER SIMILAR
TO THE ONE SHOWN BELOW:
struct structname { member1; member2; …. membern;};
struct structname *ptrvar;

Dr. M Tariq Banday, University of Kashmir, Srinagar

15
11/01/17

USER DEFINED DATA TYPES – STRUCTURES & POINTERS


• A pointer to a structure variable may be declared in a manner similar to the one shown below:
struct structname { member1; member2; …. membern;};
struct structname *ptrvar;
• Consider also a normal structure variable deceleration
struct structname svar;
• We can assign the address of structure variable to the pointer variable ptrvar by writing ptrvar=&svar;
• The members of the structure variable svar can be accessed by writing svar.member or (*ptrvar).member.
• A dash greater than operator (->) can also be used with structure type pointer variables to access the
individual members.
• Hence a member can be accessed as ptrvar->member
• In case of nested structures a submember can be accessed by writing as ptrvar->member.submember.
• In case the member is an array, the individual element can be accessed by writing ptrvar-

Lecture Notes
>member[expression].

Dr. M Tariq Banday, University of Kashmir, Srinagar

Dr. M Tariq Banday


University of Kashmir, Srinagar
USER DEFINED DATA TYPES – STRUCTURES & POINTERS
struct date { int day; int month; int year; };
struct student { int rollno; char fname[10]; struct date dob;};
struct student S={1,”Bilal”, {1,1,1990}};
struct student *PS;
PS=&S;

With respect to the above statements, following expressions evaluate to the shown values:
PS = 0F00 S =*PS = 1 *PS = 1 &S.rollno = 0F00
&S.fname = 0F02 &S.fname[1] = 0F03 S.rollno = 1 S.fname = OF02
S.fname[1] = I (*PS).rollno=1 (*PS).fname[1]=I PS->rollno=1
S.dob.year=1990 (*PS).dob.year=1990 PS->dob.year=1990 &PS->dob.day=0F0C

Dr. M Tariq Banday, University of Kashmir, Srinagar

16
11/01/17

USER DEFINED DATA TYPES – STRUCTURES & POINTERS


• Example - Processing a structure variable through a pointer. An array of structures is processed
with the help of a pointer to structure.

void main()
{
struct Marks { int rollno; int marksp1; int marksp2;};
struct Marks ClassA[5];
Struct Marks *ptr, *ptrH, *ptrL;
for(ptr=classA;ptr<ClassA+5;ptr++){ printf(“\Roll No: “); scanf(“%d”,ptr->rollno); printf(“\nMarks
p1”); scanf(“%d”, ptr->marksp1); printf(“\nMarks p2”); scanf(“%d”, ptr->marksp2);}
ptrH=ptrL=ClassA; ptr=ClassA+1;
while(ptr<ClassA+5) { if(ptrH->marksp1+ptrH->marksp2<ptr->marksp1+ptr->marksp2) ptrH=ptr;
if(ptrL->marksp1+ptrL->marksp2<ptr->marksp1+ptr->marksp2) ptrL=ptr;}
printf(“\nHighest Marks %d secured by student bearing roll no %d”, ptrH->marksp1+ptrH-
>marksp2, ptrF->rollno);
printf(“\nLowest Marks %d secured by student bearing roll no %d”, ptrL->marksp1+ptrL->marksp2,
ptrL->rollno);

Lecture Notes
}

Dr. M Tariq Banday, University of Kashmir, Srinagar

Dr. M Tariq Banday


University of Kashmir, Srinagar
USER DEFINED DATA TYPES – STRUCTURES & POINTERS
• Example - Processing a structure variable through a pointer. Dynamic Memory Allocation.

struct ITEM {char Code[10]; int Cost; };


void main()
{
struct ITEM *I, *ptr;
int No, TotalCost = 0;
printf(“\n How many Items: “); scanf(“%d”, &No);

I = (struct ITEM*) malloc(sizeof(struct ITEM)*No);


If(!I) {printf(“\nError in Memory Allocation”); exit(1);}

for(ptr=I;ptr<I+No;ptr++) { printf(“\nItem Code ?”); gets(ptr->Code); fflush(stdin);


printf(“\nItem Cost ?”); scanf(“%d”, &ptr->Cost);
TotalCost = TotalCost+ ptr->Cost;
}
printf(“\nTotal cost of all products = %d”, TotalCost);
free(I);
}
Dr. M Tariq Banday, University of Kashmir, Srinagar

17
11/01/17

USER DEFINED DATA TYPES – STRUCTURES & POINTERS


• Pointer as a structure member.
• It is possible to include a pointer as a structure member. In such a case memory must be
allocated memory to each such structure member. E.g.

• struct Account { int ActNo; char *Name; char *Address; long Amount;};
• struct Account A1;

A1.ActNo = 802
A1.Amount = 3000;

A1.Name = (char*) malloc(sizeof(char)*10);


Strcpy(A1.Name, “Bilal”);

A1.Address = (char*) malloc(sizeof(char)*10);


Strcpy(A1.Address, “Srinagar”);

Lecture Notes
Dr. M Tariq Banday, University of Kashmir, Srinagar

Dr. M Tariq Banday


University of Kashmir, Srinagar
USER DEFINED DATA TYPES – STRUCTURES & POINTERS
• Pointer as a structure member

struct RECORD { char *Name; int Age; };


void main()
{
struct RECORD R;
R.Name = (char*) malloc (sizeof(char) * 10);
printf(“\nEnter Name :”); gets(N.Name); fflush(stdin);
printf(“\nEnter Age:”); scanf(“%d”,&N.Age); fflush(stdin);
printf(“\nName = %s”, R.Name);
printf(“\nAge = %d”, R.Age);
getch();
}

Dr. M Tariq Banday, University of Kashmir, Srinagar

18
11/01/17

USER DEFINED DATA TYPES – STRUCTURES & POINTERS


• pointer as a structure member gets(temp);
l=strlen(temp);
struct student { char *name; ptr->name=(char*) malloc(sizeof(char)*l);
int rollno;}; fflush(stdin);
void main() printf(“\nrollno?”);
{ scanf(“%d”, &ptr->rollno);
strcut student *s, *ptr; }
int max, len;
char *temp; free (temp);
temp = (char*) malloc(sizeof(char)*20); printf(“\n\nlist of students ….);
printf(“how many students);
scanf(“%d”, &max); for(ptr=s; ptr<s+max; ptr++)
s= (struct student *) malloc(sizeof(struct printf(“\n%s”, tr->name);
student)*max);
for(ptr=s; ptr<s+max; ptr++)
for(ptr=s; ptr<s+max; ptr++) free(ptr->name);
{ freee(s);

Lecture Notes
printf(“\nname ?”); }

Dr. M Tariq Banday, University of Kashmir, Srinagar

Dr. M Tariq Banday


University of Kashmir, Srinagar
USER DEFINED DATA TYPES – STRUCTURES & POINTERS
• POINTER AS A STRUCTURE MEMBER
• PROGRAMME DEMONSTRATING POINTING OF A
s2.rollno);

POINTER TYPE STRUCTURE MEMBER WHEN s2.rollno=20;


THEY ARE COPIED. strcpy(s2.name,s1.name);

struct student { printf(“\n name = %s roll no = %d”, s1.name,


char *name; s1.rollno);
int rollno; printf(“\n name = %s roll no = %d”, s2.name,
}; s2.rollno);

void main() s2.name=(char*) malloc(sizeof(char)*10);


{
struct student s1 = {“bilal”, 10}; strcpy(s2.name,s1.name);
struct student s2;
printf(“\n name = %s roll no = %d”, s1.name,
printf(“\n name = %s roll no = %d”, s1.name, s1.rollno);
s1.rollno); printf(“\n name = %s roll no = %d”, s2.name,
s2.rollno);
printf(“\n name = %s roll no = %d”, s2.name, }
Dr. M Tariq Banday, University of Kashmir, Srinagar

19
11/01/17

USER DEFINED DATA TYPES – STRUCTURES WITH TYPEDEF


• Typedef Statement

• Typedef is a storage class specifier which defines identifiers that name types and does
not declare objects.
• These identifiers are called typedef names.
• Once an typedef name is defined, it is syntactically equivalent to a type specifier
keyword for the associated type.
• Although typedef names are usually created for user defined data types created with
struct keywor, yet typedef names can also be created for inbuilt data types. The
syntax for using typedef is as follows:
Typedef type newdatatypename
E.G
typedef int INTEGER; INTEGER Num, *P;

Lecture Notes
typedef float real; real Rate, temp;

Dr. M Tariq Banday, University of Kashmir, Srinagar

Dr. M Tariq Banday


University of Kashmir, Srinagar
USER DEFINED DATA TYPES – STRUCTURES WITH TYPEDEF
• typedef example

strcut record { typedef record {


int rollno; int rollno;
char name[20]; char name[20];
int marks; int marks;
}; } student;

typedef struct record struct record s1; or


student;
student s1;
or
Dr. M Tariq Banday, University of Kashmir, Srinagar

20
11/01/17

www.banday.in
USER DEFINED DATA TYPES – BITFIELDS

www.banday.in
• A bit field is a set of adjacent bits within a single word of memory. (A word being
a single implementation defined storage unit).
• Bit fields provide exact amount of bits required for storage of values.
• Some data items in a program may have only a limited domain of values.
Declaring such data items as individual variables will allocate at least a word
from memory for each such variable, thus wasting memory. E.g. a Flag indicating a
true value by 1 and false value by 0 requires only one bit in memory. Declaring it
as a variable of type int will allocate 16 bits for it. Similarly an integer variable
www.banday.in

whose value can range between 0 to 7 only requires three bits in memory.
• Bit fields provide a method for packing such data items in an individual word(s) of
memory. Thus multiple data items may be allocated memory from single word of

Lecture Notes memory.


Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in

Dr. M Tariq Banday


University of Kashmir, Srinagar
www.banday.in
USER DEFINED DATA TYPES – BITFIELDS

www.banday.in
• The minimum amount of memory allocated is a word even if the total amount of
bits required by the data items packaged int a group is less that the no of bits in
a word.
• In case it is more that a word but less that its integer multiply the amount of
memory allocated will remain the immediate next integer multiply.
• Bit fields are defined as the members of a structure in a structure definition which
can be later accessed individually by method similar to other structure members.
• Each member deceleration (a bit field) includes a colon (:) and unsigned integer as
www.banday.in

specifications indicating it to be a bit field and the size in bits respectively.


• Bits may be allocated from left to right or right to left from the reserved word(s)
which is compiler dependent.

Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in

21
11/01/17

www.banday.in
USER DEFINED DATA TYPES – BITFIELDS

www.banday.in
• A bit field can only be defined from an integer or an unsigned word. Some
compilers also permit allocation of bits from long integer and character.
• Bit fields can be accessed in a manner same as other structure members are
accessed, however, there are certain restrictions on the use of bit fields which
include:
• Bit fields cannot be arrays, i.e. a member declared as a bit field cannot be an array.
• The use of the address operator (&) is not allowed with a bit field.
• A bit field cannot be accessed via a pointer.
www.banday.in

• A function’s return data type cannot be a bit field.

Lecture Notes
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in

Dr. M Tariq Banday


University of Kashmir, Srinagar
www.banday.in
USER DEFINED DATA TYPES – BITFIELDS

www.banday.in
• Example: bit field definitions & deceleration
struct sample {
unsigned a: 1;
• This defines four bit fields named a, b, c and d, of 1, 3, 2 and 1 bits
unsigned b: 3;
each in a structure named sample. Thus as many as 7 bits are
unsigned c: 2;
required for storing the values of these bit fields.
unsigned d: 1
};
• Thus a deceleration struct sample s = {0,3,2,1}; will reserve one word (usually 16 bits) from memory
abd allocate bits as described in the bit field definition to each bit field. The bits may be allocated from left
to right or from right to left depending upon the compiler and machine.
www.banday.in

15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
1 1 0 0 1 1 0
Unused Bits d c b a
• As can be seen from the graphics only seven bits are committed while as remaining 9 bits remain
uncommitted. Besides these bit fields are also initialized to the values shown.
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in

22
11/01/17

www.banday.in
USER DEFINED DATA TYPES – BITFIELDS

www.banday.in
• Example: bit field definitions & deceleration
struct sample {
unsigned a: 6;
• This defines five bit fields named a, b, c, d and e, of 6. 4, 5, 4 and 5
unsigned b: 4;
bits each in a structure named sample.
unsigned c: 5;
unsigned d: 4;
unsigned e: 5;
};
• Thus a deceleration struct sample s = {6,4,5,4,5}; will reserve two words from memory (in case the
word size is 16 bits). The first three bit fields namely a, b and c will be allocated memory from the first word
www.banday.in

and the last two namely d and e will be forced to second word.
31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

Lecture Notes
Unused Bits e d c b a

Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in

Dr. M Tariq Banday


University of Kashmir, Srinagar
www.banday.in
USER DEFINED DATA TYPES – BITFIELDS

www.banday.in
• Example: bit field definitions & deceleration

Sometimes, it may be desired to align a bit field to a new word and skipping the available
bits within the current word.
Consider definition of three bit fields of 5 bits each, thus requiring a total of 15 bits which
can be reserved from one word. However, if it is desired to align the last bit field to another
word, the following definition may be used:
struct sample { struct sample {
unsigned a: 5; unsigned a: 5;
unsigned b: 6; unsigned b: 6;
Unsigned Filler: 6;
www.banday.in

Unsigned : 0;
unsigned c: 5; unsigned c: 5;
}; };
• To align the bit field, a filler or an unnamed field with zero width can be used.

Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in

23
11/01/17

www.banday.in
USER DEFINED DATA TYPES – BITFIELDS

www.banday.in
• Example: printf(“\nrollno ? :”);
scanf(“%d”, &temp); s[i].rollno=temp;
struct marks { print(“\nname ?”);
unsigned th: 7; gets(s[i].name); fflush(stdin);
unsigned pr: 7; printf(“\ntheory marks ?”);
unsigned tot: 8; scanf(“%d”,&temp); s[i].m.th=temp;
unsigned per: 7; …...
unsigned res: 3; .......
}; s[i].m.tot=s[i].m.th + s[i].m.pr;
typedef struct { }
unsigned rollno: 4;
char fname[10]; for (i=0;i<10;i++)
struct marks m; {
} student;
www.banday.in

printf(“\nrollno = %d”, s[i].rollno);


void main() …...
{ .....
int temp; printf(“\ntotal marks = %u”,s[i].m.tot);
student s[10]; }

Lecture Notes
for (i=0;i<10;i++)
{
}
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in

Dr. M Tariq Banday


University of Kashmir, Srinagar
www.banday.in
USER DEFINED DATA TYPES – STRUCTURES

www.banday.in
• Passing Structures to Functions
• C permits a function to pass structures as arguments to
another function and also permits a function to return a
structure.
• Structures can be passed to function in three ways:
• By passing individual members of structure, e.g.
www.banday.in

• By passing a copy of the entire structure


• By passing a pointer to the structure

Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in

24
11/01/17

www.banday.in
USER DEFINED DATA TYPES – STRUCTURES

www.banday.in
• Passing Structures to Functions - passing individual members
• This method is the most elementary one and has no or very little practical significance because
it becomes unmanagable and inefficient when dealing with a large structure.
#include <stdio.h> printdistance(d1.feet, d1.inch);
typedef { printdistance(d2.feet, d2.inch);
int feet; }
int inch;
} distance; void printdistance (int f, int i)
www.banday.in

void printdistance (int f, int i); {


void main() printf(“\n feets = %d”, f);
{ printf(“\n inchs = %d”, i);

Lecture Notes distance d1 = {10,5}, d2 = {8,9};


Dr. M Tariq Banday, University of Kashmir, Srinagar
}
www.banday.in

Dr. M Tariq Banday


University of Kashmir, Srinagar
www.banday.in
USER DEFINED DATA TYPES – STRUCTURES

www.banday.in
• Passing Structures to Functions - passing copy of the entire structure
• It is much efficient an manageable.

#include <stdio.h> void main()


typedef { {
int feet; distance d1 = {10,5}, d2,d3;
int inch; d2=readdistance();
} distance; d3=adddistances(d1,d2);
void printdistance (distance d); printdistance(d1);
www.banday.in

distance readdistance(void); printdistance(d2);


distance adddistances(distance d1, printdistance(d3);
distance d2); }

Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in

25
11/01/17

www.banday.in
USER DEFINED DATA TYPES – STRUCTURES

www.banday.in
• Passing Structures to Functions - passing copy of the entire structure
• It is much efficient an manageable.
void printdistance (distance d) distance adddistances(distance d1, distance d2)
{ {
printf(“\nfeets = %d”, d.feet); distance temp;
printf(“\ninchs = %d”, d.inch); temp.feet=d1.feet+d2.feet;
} temp.inch=d1.inch+d2.inch;
distance readdistance(void) while(temp.inch>=12)
{ {
www.banday.in

distance d; temp.feet-=12; temp.inch--;


printf(“\nEnter feets”); scanf(“%d”, &d.feet); }
printf(“\nEnter inchs”); scanf(“%d”, &d.inch); return(temp);

Lecture Notes
return(d); }
}
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in

Dr. M Tariq Banday


University of Kashmir, Srinagar
www.banday.in
USER DEFINED DATA TYPES – STRUCTURES

www.banday.in
• Passing Structures to Functions – by passing copy pointer to a structure
• It is much efficient an manageable.

#include <stdio.h> void main()


typedef { {
int feet; distance d1 = {10,5}, d2,d3;
int inch; readdistance(&d2);
} distance; adddistances(&d1,&d2,&d3);
void printdistance (distance *d); printdistance(&d1);
www.banday.in

void readdistance(distance *d); printdistance(&d2);


void adddistances(distance *d1, printdistance(&d3);
distance *d2, distance *d3); }

Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in

26
11/01/17

www.banday.in
USER DEFINED DATA TYPES – STRUCTURES

www.banday.in
• Passing Structures to Functions – by passing pointer to a structure
• It is much efficient an manageable.
void printdistance (distance *d);
{ void adddistances(distance *d1, distance *d2,
printf(“\n feets = %d”, d->feet); distance *d3);
printf(“\n inchs = %d”, d->inch); {
} d3->feet=d1->feet+d2->feet;
void readdistance(distance *d); d3->inch=d1->inch+d2->inch;
{ while(d3->inch>=12)
www.banday.in

printf(“\n Enter feets”); scanf(“%d”, &d->feet); {


d3->feet-=12; d3->inch--;
printf(“\n Enter inchs”); scanf(“%d”, &d->inch); }

Lecture Notes
} }

Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in

Dr. M Tariq Banday


University of Kashmir, Srinagar
www.banday.in
USER DEFINED DATA TYPES – STRUCTURES

www.banday.in
• Exercise: Using structures and functions, add as many as 10 distances
stored in an array.
• Exercise: Using structures and functions repeat the student program to
calculate marks and grades.
www.banday.in

Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in

27
11/01/17

www.banday.in
USER DEFINED DATA TYPES – UNIONS

www.banday.in
• A union data type is borrowed from structures data type and is similar
to variant record type of Pascal language.
• A union is essentially a structure in which all of the fields overlay each
other and only one can be used at a time. Members of the union share
memory.
• The size of the union is the maximum of the sizes of its individual
members, whereas the size of the structure is the sum of the sizes of its
www.banday.in

individual members.
• Unlike structure variables, for a union variable all members begin at

Lecture Notes
offset zero from the base address.
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in

Dr. M Tariq Banday


University of Kashmir, Srinagar
www.banday.in
USER DEFINED DATA TYPES – UNIONS

www.banday.in
• Although a union can have many members but it can hold only one
member at a time.
• Unions provide a way to manipulate different kinds of data in a single
area of storage. i.e. a single variable that can hold any one of several
data types.
• The method of defining a union is same as that of a structure except a
distinction that the struct keyword is replaced by union keyword. The
www.banday.in

members of union may include inbuilt or other user defined data types
like structures.
• Similarly union variable deceleration is similar to that of structures.
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in

28
11/01/17

www.banday.in
USER DEFINED DATA TYPES – UNIONS

www.banday.in
• A union may be initialized only with a value of the type of its first
member.
• All operations that are permitted on a structure variable are
permissible with union variables including assignment, accession union
members, use of address (&) operator, (->) operator, etc.
• Unions can be nested in structures and visa versa.
• It is permissible to have union of structures, and bit fields in unions.
www.banday.in

Lecture Notes
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in

Dr. M Tariq Banday


University of Kashmir, Srinagar
www.banday.in
USER DEFINED DATA TYPES – UNIONS

www.banday.in
• Consider the following example definition of Union:
union Example {
int ival;
float fval;
0F01 0F02 0F03 0F04 0F05 0F06 0F07 0F08
double dval;
ival
char *Sval;
fval
};
dval
union Example u1 = 10;
Sval
union Example u2;
www.banday.in

&u1 = &u1.ival = &u1.fval = &u1.dval = &u1.SVal = 0F01


u1.ival = 10
Using a statement such as u1.fval = 33.50 will invalidate u1.ival as only one member
of the union can hold a valid value.
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in

29
11/01/17

www.banday.in
USER DEFINED DATA TYPES – UNIONS

www.banday.in
• Example
union allowance{
float GPF;
float PF;
};
www.banday.in

Lecture Notes
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in

Dr. M Tariq Banday


University of Kashmir, Srinagar
www.banday.in
USER DEFINED DATA TYPES – ENUMERATION

www.banday.in
• An enumeration is a user defined data type with values ranging over a set of named
constants. These constants are called enumeration variables and are of type int.
• An enumeration variable can be assigned any value from the corresponding set of
enumerators.
• Enumerators in the same scope must be distinct from each other and also from ordinary
variable names.
• The values however can be same for two enumerators. The general syntax for defining an
enumeration is:
• enum tag { enumurator1=[value1], enumurator2=[value2], …......
www.banday.in

enumuratorn=[valuen]};
• Enumuration variables can be declared with the following syntax:
• Storageclass enum tag variable1, varaible2, ....variablen;

Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in

30
11/01/17

www.banday.in
USER DEFINED DATA TYPES – ENUMERATION

www.banday.in
• Examples
• enum DAYS{SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY};
• The constant values assigned to each enumerator are 0, 1, 2, 3, 4, 5, 6, respectively.
• enum DAYS BEGIN, END
• Assignments in the program can be used like
• Begin = Monday
• End = Sunday
• enum DAYS{SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY}
Begin, End;
www.banday.in

in this case the name of the enum DAYS is optional

Lecture Notes
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in

Dr. M Tariq Banday


University of Kashmir, Srinagar
www.banday.in
USER DEFINED DATA TYPES – ENUMERATION

www.banday.in
• Examples
• enum {NO, YES} Answer;
• enum {OM, SC, ST, OBC} Category ;
• enum {Singly, Married, Widowed, Divorced} Status ;
• enum {False, True} TF;
• enum color {RED =10, GREEN, BLUE};
• enum color Foreground, Background
#include <stdio.h>
enum {NO, YES} Answer;
void main()
www.banday.in

{
Answer = NO;
printf(“The answer is %d”, Answer);
}
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in

31
11/01/17

www.banday.in
BIT WISE OPERATORS

www.banday.in
• Bitwise operators permit manipulation of bits stored in the memory
which is considered to be a low-level feature found mostly in low level
programming languages such as assembly languages.
• These operators treat variables as combinations of bits rather than as
numbers.
• They are useful in accessing the individual bits in memory such as the
screen memory etc.
www.banday.in

• Only integers can be operated upon by bitwise operators.

Lecture Notes
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in

Dr. M Tariq Banday


University of Kashmir, Srinagar
www.banday.in
BIT WISE OPERATORS

www.banday.in
Operator Meaning Example
~ Ones Complement ~0XF1 returns 0XFF0E (hex)
~0361 returns 0177416 (octal)
~11110011 returns 00001100 (binary)
& Bitwise AND 0XF1 & 0X35 returns 0X31 (hex)
0361 & 0065 returns 061 (octal)
11110011 & 00110101 returns 00110011 (binary)
| Bitwise OR
^ Bitwise XOR
<< Left Shift
>> Right Shift
www.banday.in

&= Bitwise AND and assign


|= Bitwise OR and assign
^= Bitwise XOR and assign
<<= Left Shift then assign
>>= Right Shift then assign
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in

32
11/01/17

www.banday.in
BIT WISE OPERATORS

www.banday.in
Decimal to Binary Conversion using Bit-Wise Operators
#include <stdio.h>
int main()
{
int n, c, k;
printf("enter an integer in decimal number system\n");
scanf("%d", &n); printf("%d in binary number system is:\n", n);
for (c = 31; c >= 0; c--)
{
k = n >> c;
if (k & 1)
printf("1");
www.banday.in

else
printf("0");
}
printf("\n");

Lecture Notes
return 0;
}
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in

Dr. M Tariq Banday


University of Kashmir, Srinagar

ANY QUESTIONS
THANK YOU

33

You might also like