SlideShare a Scribd company logo
1 of 64
COM1407
Computer Programming
Lecture 12
Structures, Unions & Dynamic Memory
Allocation
K.A.S.H. Kulathilake
B.Sc. (Hons) IT, MCS , M.Phil., SEDA(UK)
Rajarata University of Sri Lanka
Department of Physical Sciences
1
Objectives
• At the end of this lecture students should be able to;
▫ Define, initialize and access to the C stuctuers.
▫ Develop programs using structures in arrays and
functions.
▫ Use structures within structures and structures as
pointers.
▫ Define, initialize and access to the C unions.
▫ Compare and contrast C structures and unions.
▫ Define memory allocation and de-allocation methods
in C.
▫ Develop programs using memory allocation functions.
▫ Apply taught concepts for writing programs.
2
Introduction
• How do we keep the group of data items that are
related but have different data types?
• For example, suppose that along with the game
scores, we want to store the name of each player, the
country from which they come and their ages.
• Here, the score is a float, the player and the country
are character strings and the age is an integer.
• We would like to store these four items together as
one unit and to handle and process them together as
a group.
• In order to do this we can use structure data type.
3
Defining a Structure
• The keyword use to define structure data type is
struct.
• For our needs, we can define the structure as
shown below.
struct Participant
{
char Name[20];
char Country[25];
float Score;
int Age;
};
4
Defining a Structure (Cont…)
• struct is a keyword and the Participant is a name or
tag that we provided.
• All that we are doing is defining a structure called
struct Participant.
• We are not creating a variable instead we are
creating a new data type that includes or aggregate
other C and C++ data types.
• You can think of this as a structure template from
which structure variables may be defined.
• The order in which the structure members are
defined is not important.
5
Declaring Structure Variables
• The following code shows how structure
variables are declared.
struct Participant Player1;
Struct Participant Player2;
or both together
struct Participant Player1, Player1;
6
Declaring Structure Variables (Cont…)
7
Declaring Structure Variables (Cont…)
struct date
{
int month;
int day;
int year;
} todaysDate, purchaseDate;
• Defines the structure date and also declares the
variables todaysDate and purchaseDate to be of
this type.
8
Initializing Structure Variables
• The following code shows how structure
variables initialization.
struct Participant Player1, Player2 =
{"Korea", "Kenya", 4.6, 19};
9
Initializing Structure Variables (Cont…)
10
Player1 is defined and has
four members.
Player2 is also defined and
its four members are
initialized.
Here, the order is important.
They should be initialized in
the same order that the
structure members are
defined as shown in the
Figure.
struct Participant Player1,
Player2 =
{"Korea", "Kenya", 4.6, 19};
Initializing Structure Variables (Cont…)
• You can also assign initial values to the variables in
the normal fashion.Thus,
struct date
{
int month;
int day;
int year;
} todaysDate = { 1, 11, 2005 };
• Defines the structure date and the variable
todaysDate with initial values as indicated.
11
Accessing Values
• With structures, we must follow the variable
name by a period, followed by the member
name to access one member.
• This operator is known as member access
operator (.).
• For example, Player2.Score is equal to 4.60.
12
Accessing Values (Cont…)
#include <stdio.h>
struct Participant
{
char Name[20];
char Country[25];
float Score;
int Age;
};
int main ()
{
struct Participant Player1,
Player2= {"Korea", "Kenya", 4.6, 19};
printf ("%sn", Player1.Name);
printf ("%sn", Player2.Name);
printf ("%in", Player2.Age);
return 0;
}
13
Player1 is not initialized.
You do not get a value for
this statement.
Accessing Values (Cont…)
#include <stdio.h>
struct Participant
{
char Name[20];
char Country[25];
float Score;
int Age;
};
int main ()
{
struct Participant Player1 =
{"Sugath", "Sri Lanka",5.5, 20};
struct Participant Player2 =
{"Korea", "Kenya", 4.6, 19};
printf ("%s : %sn", Player1.Name, Player1.Country);
printf ("%s : %sn", Player2.Name, Player2.Country);
return 0;
}
14
Point to Note in Structure Initialization
#include <stdio.h>
int main ()
{
struct time
{
int hour;
int min;
int sec;
};
struct time time1 = {12,10};
printf ("%in",time1.hour);
printf ("%in",time1.min);
printf ("%in",time1.sec);
return 0;
}
15
sets time1.hour to 12 and
time1.minutes to 10 but
gives no initial value to
time1.seconds.
In such a case, its default
initial value is undefined.
Exercise
Write a program to store day,
month and year into a structure.
Print “Wish you a happy new year ”
if both month and day of a
particular day is equal to 1
16
Exercise
#include <stdio.h>
struct Day
{
int year;
int month;
int day;
};
int main ()
{
struct Day today;
today.month = 1;
today.day = 1;
today. year= 2017;
if (today.month == 1 && today.day == 1)
printf ("Wish you a happy new year");
return 0;
}
17
Using Structures in Expressions
#include <stdio.h>
int main (void)
{
struct date
{
int month;
int day;
int year;
};
struct date today, tomorrow;
const int daysPerMonth[12] =
{ 31, 28, 31, 30, 31, 30,31, 31, 30, 31, 30, 31 };
printf ("Enter today's date (mm dd yyyy): ");
scanf ("%i%i%i", &today.month, &today.day, &today.year);
18
Using Structures in Expressions (Cont…)
if ( today.day == daysPerMonth[today.month - 1] && today.month !=12 ) {
tomorrow.day = 1;
tomorrow.month = today.month+1;
tomorrow.year = today.year;
}
else if ( today.month == 12 && today.day == 31 ) {
tomorrow.day = 1;
tomorrow.month = 1;
tomorrow.year = today.year + 1;
}
else {
tomorrow.day = today.day+1;
tomorrow.month = today.month;
tomorrow.year = today.year;
}
printf ("Tomorrow's date is %i/%i/%.2i.n",
tomorrow.month,tomorrow.day, tomorrow.year % 100);
return 0;
}
19
Array of Structures
• C does not limit you to storing simple data types
inside an array; it is perfectly valid to define an
array of structures.
• For example,
struct date birthdays[15];
• defines the array birthdays to contain 15
elements of type struct date.
20
Array of Structures (Cont…)
struct Participant Player[2];
• This will create an array called Player[ ] with
only 2 slots, where each slot is a structure of type
struct Participant.
21
Array of Structures (Cont…)
• Initializing Player array
struct Participant Player[2]= {
{"Korea", "Kenya", 4.6, 19},
{“Mary", "Australia", 4.8, 20}
};
22
Array of Structures (Cont…)
#include <stdio.h>
struct Participant
{
char Name[20];
char Country[25];
float Score;
int Age;
};
int main ()
{
struct Participant Player[2] = {
{"Sugath", "Sri Lanka",5.5, 20},
{"Korea", "Kenya", 4.6, 19}};
printf ("%s : %sn", Player[0].Name, Player[0].Country);
printf ("%s : %sn", Player[1].Name, Player[1].Country);
return 0;
}
23
Array of Structures (Cont…)
#include <stdio.h>
int main ()
{
struct time
{
int hour;
int min;
int sec;
};
struct time runTime1 [5] ={
{12, 0, 0}, {12, 30, 0}, {13, 15, 0} };
printf ("%in",runTime1[0].hour);
printf ("%in",runTime1[0].min);
printf ("%in",runTime1[0].sec);
return 0;
}
24
Structures Containing Structures
• We can also create a structure based on other structures.
•
#include <stdio.h>
struct Participant
{
char Name[20];
char Country[25];
float Score;
int Age;
};
struct Team
{
struct Participant captain;
int wins;
int losses;
struct Participant member[2];
};
25
Structures Containing Structures
(Cont…)
int main()
{
struct Team slTeam = {{"Aravinda","LKR", 8.8,25},
10,
2,
{
{"Kumara","LKR", 8.0,25},
{"Dilip","LKR", 7.8,25}
}
};
printf("Captain : %sn",slTeam.captain.Name);
printf("Team Membersn");
printf("%sn", slTeam.member[0].Name);
printf("%sn", slTeam.member[1].Name);
printf("Match ScorenWins : %inLosses :%in",
slTeam.wins, slTeam.losses);
return 0;
}
26
Structures Containing Structures
(Cont…)
#include <stdio.h>
struct date
{
int date;
int month;
int year;
};
struct Employee
{
char ename[20];
int ssn;
float salary;
struct date doj;
}emp = {"Pritesh",1000,1000.50,{22,6,1990}};
27
Structures Containing Structures
(Cont…)
int main(int argc, char *argv[])
{
printf("nEmployee Name : %s",emp.ename);
printf("nEmployee SSN : %d",emp.ssn);
printf("nEmployee Salary : %f",emp.salary);
printf("nEmployee DOJ : %d/%d/%d",
emp.doj.date,emp.doj.month,emp.doj.year);
return 0;
}
28
Structures Containing Structures
(Cont…)
int main()
{
struct Team team1 ={
{"Jasmine", "Cambodia", 3.5, 22},
5,
2,
{{"Michael", "Cambodia", 5.2, 20},
{"Leonard", "Cambodia", 4.0, 24}}
};
printf ("%sn", team1.Captain.Name);
printf ("%sn", team1.Player[0].Country);
return 0;
}
29
Functions & Structures
#include <stdio.h>
#include <string.h>
struct Mobile
{
char Make[20];
int Year;
};
struct Mobile FindYear(char Name[ ]);
void PrintOldest(struct Mobile Auto1,
struct Mobile Auto2);
30
Functions & Structures (Cont…)
struct Mobile FindYear(char Name[])
{
struct Mobile Car;
printf("What year is the %s? ", Name);
scanf("%d", &Car.Year);
printf("Car.Year = %dn", Car.Year);
strcpy(Car.Make, Name);
return Car;
}
31
Functions & Structures (Cont…)
void PrintOldest(struct Mobile Auto1,
struct Mobile Auto2)
{
if(Auto1.Year < Auto2.Year)
printf("The oldest car is the
%sn", Auto1.Make);
else if(Auto1.Year > Auto2.Year)
printf("The oldest car is the
%sn", Auto2.Make);
else
printf("They are both the same
age!n");
}
32
Functions & Structures (Cont…)
int main()
{
struct Mobile Car1, Car2;
Car1 = FindYear("Toyota");
Car2 = FindYear("Nissan");
PrintOldest(Car1, Car2);
return 0;
}
33
Pointers to Structures
• You can define pointers to structures in the same way as
you define pointer to any other variable:
struct Books *struct_pointer;
• Now, you can store the address of a structure variable in
the above defined pointer variable.
• To find the address of a structure variable, place the '&';
operator before the structure's name as follows:
struct_pointer = &Book1;
• To access the members of a structure using a pointer to
that structure, you must use the → operator as follows:
struct_pointer->title;
34
Pointers to Structures (Cont…)
#include <stdio.h>
#include <string.h>
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
/* function declaration */
void printBook( struct Books *book );
35
Pointers to Structures (Cont…)
int main( )
{
struct Books Book1;/*Declare Book1 of type Book*/
struct Books Book2;/*Declare Book2 of type Book*/
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;
36
Pointers to Structures (Cont…)
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
/* print Book1 info by passing address of Book1 */
printBook( &Book1 );
/* print Book2 info by passing address of Book2 */
printBook( &Book2 );
return 0;
}
37
Pointers to Structures (Cont…)
void printBook( struct Books *book )
{
printf( "Book title : %sn", book->title);
printf( "Book author : %sn", book->author);
printf( "Book subject : %sn", book->subject);
printf( "Book book_id : %dn", book->book_id);
}
38
Union
• A union is a block of memory that is used to hold data
items of different types.
• In C, a union is similar to a structure, except that the
data items saved in the union are overlaid in order to
share the same memory location.
• That is, they all share the same starting address, unlike a
structure where each member gets its own area of
memory.
• 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-purpose.
39
Defining a Union
• To define a union, you must use
the union statement in the same way as you did
while defining a structure.
• The union statement defines a new data type with
more than one member for your program.
• At the end of the union's definition, before the final
semicolon, you can specify one or more union
variables but it is optional.
union Data {
int i;
float f;
char str[20];
} data;
40
Defining a Union (Cont…)
• Now, a variable of Data type can store an integer, a
floating-point number, or a string of characters.
• It means a single variable, i.e., same memory
location, can be used to store multiple types of data.
• You can use any built-in or user defined data types
inside a union based on your requirement.
• The memory occupied by a union will be large
enough to hold the largest member of the union.
• For example, in the above example, Data type will
occupy 20 bytes of memory space because this is the
maximum space which can be occupied by a
character string.
41
Defining a Union (Cont…)
#include <stdio.h>
union Data
{
int i;
float f;
char str[20];
};
int main( )
{
union Data data;
printf( "Memory size occupied by data : %dn",
sizeof(data));
return 0;
}
42
Accessing Union Members
#include <stdio.h>
#include <string.h>
union Data
{
int i; float f; char str[20];
}data;
int main( )
{
data.i = 10; data.f = 220.5;
strcpy( data.str, "C Programming");
printf( "data.i : %in", data.i);
printf( "data.f : %fn", data.f);
printf( "data.str : %sn", data.str);
return 0;
}
43
To access any member of a union,
we use the member access
operator (.).
Here, we can see that the values
of i and f members of union got
corrupted because the final value
assigned to the variable has
occupied the memory location and
this is the reason that the value
of str member is getting printed
very well.
Accessing Union Members (Cont…)
#include <stdio.h>
#include <string.h>
union Data {
int i; float f;
char str[20];
};
int main( ) {
union Data data;
data.i = 10;
printf( "data.i : %dn", data.i);
data.f = 220.5;
printf( "data.f : %fn", data.f);
strcpy( data.str, "C Programming");
printf( "data.str : %sn", data.str);
return 0;
}
44
Memory Allocation
• In C, the exact size of array is unknown until
compile time, i.e., the time when a compiler
compiles your code into a computer understandable
language.
• So, sometimes the size of the array can be
insufficient or more than required.
• Dynamic memory allocation allows your program to
obtain more memory space while running, or to
release it if it's not required.
• In simple terms, Dynamic memory allocation allows
you to manually handle memory space for your
program.
45
Memory Allocation (Cont…)
• Although, C language inherently does not have any technique
to allocate memory dynamically, there are 4 library functions
under "stdlib.h" for dynamic memory allocation.
46
Function Use of Function
malloc()
Allocates requested size of bytes and returns a pointer first byte
of allocated space
calloc()
Allocates space for an array elements, initializes to zero and then
returns a pointer to memory
free() deallocate the previously allocated space
realloc() Change the size of previously allocated space
C malloc()
• The name malloc stands for "memory allocation".
• The function malloc() reserves a block of memory of specified size and
return a pointer of type void which can be casted into pointer of any form.
ptr = (cast-type*) malloc(byte-size)
• Here, ptr is pointer of cast-type. The malloc() function returns a pointer to
an area of memory with size of byte size. If the space is insufficient,
allocation fails and returns NULL pointer.
ptr = (int*) malloc(100 * sizeof(int));
• This statement will allocate either 200 or 400 according to size of int 2 or 4
bytes respectively and the pointer points to the address of first byte of
memory.
47
C calloc()
• The name calloc stands for "contiguous allocation".
• The only difference between malloc() and calloc() is that, malloc()
allocates single block of memory whereas calloc() allocates multiple
blocks of memory each of same size and sets all bytes to zero.
ptr = (cast-type*)calloc(n, element-size);
• This statement will allocate contiguous space in memory for an
array of n elements. For example:
ptr = (float*) calloc(25, sizeof(float));
• This statement allocates contiguous space in memory for an array of
25 elements each of size of float, i.e, 4 bytes.
48
C free()
• Dynamically allocated memory created with
either calloc() or malloc() doesn't get freed on its
own.
• You must explicitly use free() to release the
space.
free(ptr);
• This statement frees the space allocated in the
memory pointed by ptr.
49
Exercise
Write a C program to find
sum of n elements entered
by user. To perform this
program, allocate memory
dynamically using malloc()
function.
50
Exercise
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &num);
ptr = (int*) malloc(num * sizeof(int));
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
51
Exercise
printf("Enter elements of array: ");
for(i = 0; i < num; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
free(ptr);
return 0;
}
52
Exercise
Write a C program to find
sum of n elements entered
by user. To perform this
program, allocate memory
dynamically using calloc()
function.
53
Exercise
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &num);
ptr = (int*) calloc(num, sizeof(int));
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
54
Exercise
printf("Enter elements of array: ");
for(i = 0; i < num; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
free(ptr);
return 0;
}
55
C realloc()
• If the previously allocated memory is insufficient
or more than required, you can change the
previously allocated memory size using realloc().
ptr = realloc(ptr, newsize);
• Here, ptr is reallocated with size of newsize.
56
Exercise
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr, i , n1, n2;
printf("Enter size of array: ");
scanf("%d", &n1);
ptr = (int*) malloc(n1 * sizeof(int));
printf("Address of previously allocated memory: ");
57
Exercise
for(i = 0; i < n1; ++i)
printf("%ut",ptr + i);
printf("nEnter new size of array: ");
scanf("%d", &n2);
ptr = realloc(ptr, n2);
for(i = 0; i < n2; ++i)
printf("%ut", ptr + i);
return 0;
}
58
Exercise
Find Largest Element Using
Dynamic Memory Allocation -
calloc().
59
Exercise
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, num;
float *data;
printf("Enter total number of elements(1 to 100): ");
scanf("%d", &num);
data = (float*) calloc(num, sizeof(float));
if(data == NULL)
{
printf("Error!!! memory not allocated.");
exit(0);
}
60
Exercise
printf("n");
for(i = 0; i < num; ++i)
{
printf("Enter Number %d: ", i + 1);
scanf("%f", data + i);
}
for(i = 1; i < num; ++i)
{
if(*data < *(data + i))
*data = *(data + i);
}
printf("Largest element = %.2f", *data);
return 0;
}
61
Objective Re-cap
• Now you should be able to:
▫ Define, initialize and access to the C stuctuers.
▫ Develop programs using structures in arrays and
functions.
▫ Use structures within structures and structures as
pointers.
▫ Define, initialize and access to the C unions.
▫ Compare and contrast C structures and unions.
▫ Define memory allocation and de-allocation methods
in C.
▫ Develop programs using memory allocation functions.
▫ Apply taught concepts for writing programs.
62
References
• Chapter 09 - Programming in C, 3rd Edition,
Stephen G. Kochan
63
Next: Character & Strings
64

More Related Content

What's hot (20)

Reading and Writing Files
Reading and Writing FilesReading and Writing Files
Reading and Writing Files
 
Structure of a C program
Structure of a C programStructure of a C program
Structure of a C program
 
Software quality
Software qualitySoftware quality
Software quality
 
Method overloading
Method overloadingMethod overloading
Method overloading
 
String C Programming
String C ProgrammingString C Programming
String C Programming
 
Differences between c and c++
Differences between c and c++Differences between c and c++
Differences between c and c++
 
Sdlc
SdlcSdlc
Sdlc
 
Training report of C language
Training report of C languageTraining report of C language
Training report of C language
 
ccs356-software-engineering-notes.pdf
ccs356-software-engineering-notes.pdfccs356-software-engineering-notes.pdf
ccs356-software-engineering-notes.pdf
 
Our presentation on algorithm design
Our presentation on algorithm designOur presentation on algorithm design
Our presentation on algorithm design
 
Dynamic memory allocation in c
Dynamic memory allocation in cDynamic memory allocation in c
Dynamic memory allocation in c
 
C string
C stringC string
C string
 
Strings
StringsStrings
Strings
 
String c
String cString c
String c
 
Unit 1 UHV Introduction to Value Education
Unit   1 UHV Introduction to Value EducationUnit   1 UHV Introduction to Value Education
Unit 1 UHV Introduction to Value Education
 
Structure of C program
Structure of C programStructure of C program
Structure of C program
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in Java
 
Algorithm and pseudocode conventions
Algorithm and pseudocode conventionsAlgorithm and pseudocode conventions
Algorithm and pseudocode conventions
 
The Loops
The LoopsThe Loops
The Loops
 
Data types in C
Data types in CData types in C
Data types in C
 

Similar to Structures, Unions & Dynamic Memory in C

CHAPTER -4-class and structure.pptx
CHAPTER -4-class and structure.pptxCHAPTER -4-class and structure.pptx
CHAPTER -4-class and structure.pptxGebruGetachew2
 
data structure and c programing concepts
data structure and c programing conceptsdata structure and c programing concepts
data structure and c programing conceptskavitham66441
 
Data Structure & Algorithm - Self Referential
Data Structure & Algorithm - Self ReferentialData Structure & Algorithm - Self Referential
Data Structure & Algorithm - Self Referentialbabuk110
 
STRUCTURES IN C PROGRAMMING
STRUCTURES IN C PROGRAMMING STRUCTURES IN C PROGRAMMING
STRUCTURES IN C PROGRAMMING Gurwinderkaur45
 
Pf cs102 programming-10 [structs]
Pf cs102 programming-10 [structs]Pf cs102 programming-10 [structs]
Pf cs102 programming-10 [structs]Abdullah khawar
 
Data structure and algorithm notes
Data structure and algorithm notesData structure and algorithm notes
Data structure and algorithm notessuman khadka
 
C programming & data structure [arrays & pointers]
C programming & data structure   [arrays & pointers]C programming & data structure   [arrays & pointers]
C programming & data structure [arrays & pointers]MomenMostafa
 
From the proposal to ECMAScript – Step by Step
From the proposal to ECMAScript – Step by StepFrom the proposal to ECMAScript – Step by Step
From the proposal to ECMAScript – Step by StepIgalia
 
Structure and Union.ppt
Structure and Union.pptStructure and Union.ppt
Structure and Union.pptSeethaDinesh
 

Similar to Structures, Unions & Dynamic Memory in C (20)

Structures_Final_KLE (2).pptx
Structures_Final_KLE (2).pptxStructures_Final_KLE (2).pptx
Structures_Final_KLE (2).pptx
 
CHAPTER -4-class and structure.pptx
CHAPTER -4-class and structure.pptxCHAPTER -4-class and structure.pptx
CHAPTER -4-class and structure.pptx
 
Structure & union
Structure & unionStructure & union
Structure & union
 
data structure and c programing concepts
data structure and c programing conceptsdata structure and c programing concepts
data structure and c programing concepts
 
Data Structure & Algorithm - Self Referential
Data Structure & Algorithm - Self ReferentialData Structure & Algorithm - Self Referential
Data Structure & Algorithm - Self Referential
 
STRUCTURES IN C PROGRAMMING
STRUCTURES IN C PROGRAMMING STRUCTURES IN C PROGRAMMING
STRUCTURES IN C PROGRAMMING
 
structure1.pdf
structure1.pdfstructure1.pdf
structure1.pdf
 
Unit4 C
Unit4 C Unit4 C
Unit4 C
 
Pf cs102 programming-10 [structs]
Pf cs102 programming-10 [structs]Pf cs102 programming-10 [structs]
Pf cs102 programming-10 [structs]
 
Structures and Unions
Structures and UnionsStructures and Unions
Structures and Unions
 
Data structure and algorithm notes
Data structure and algorithm notesData structure and algorithm notes
Data structure and algorithm notes
 
Structures
StructuresStructures
Structures
 
structure
structurestructure
structure
 
Chapter 8 Structure Part 2 (1).pptx
Chapter 8 Structure Part 2 (1).pptxChapter 8 Structure Part 2 (1).pptx
Chapter 8 Structure Part 2 (1).pptx
 
C programming & data structure [arrays & pointers]
C programming & data structure   [arrays & pointers]C programming & data structure   [arrays & pointers]
C programming & data structure [arrays & pointers]
 
From the proposal to ECMAScript – Step by Step
From the proposal to ECMAScript – Step by StepFrom the proposal to ECMAScript – Step by Step
From the proposal to ECMAScript – Step by Step
 
Unit 5 (1)
Unit 5 (1)Unit 5 (1)
Unit 5 (1)
 
Structure and Union.ppt
Structure and Union.pptStructure and Union.ppt
Structure and Union.ppt
 
1. structure
1. structure1. structure
1. structure
 
Structure in C
Structure in CStructure in C
Structure in C
 

More from Hemantha Kulathilake

NLP_KASHK:Parsing with Context-Free Grammar
NLP_KASHK:Parsing with Context-Free Grammar NLP_KASHK:Parsing with Context-Free Grammar
NLP_KASHK:Parsing with Context-Free Grammar Hemantha Kulathilake
 
NLP_KASHK:Context-Free Grammar for English
NLP_KASHK:Context-Free Grammar for EnglishNLP_KASHK:Context-Free Grammar for English
NLP_KASHK:Context-Free Grammar for EnglishHemantha Kulathilake
 
NLP_KASHK:Evaluating Language Model
NLP_KASHK:Evaluating Language ModelNLP_KASHK:Evaluating Language Model
NLP_KASHK:Evaluating Language ModelHemantha Kulathilake
 
NLP_KASHK:Finite-State Morphological Parsing
NLP_KASHK:Finite-State Morphological ParsingNLP_KASHK:Finite-State Morphological Parsing
NLP_KASHK:Finite-State Morphological ParsingHemantha Kulathilake
 
COM1407: Program Control Structures – Repetition and Loops
COM1407: Program Control Structures – Repetition and Loops COM1407: Program Control Structures – Repetition and Loops
COM1407: Program Control Structures – Repetition and Loops Hemantha Kulathilake
 

More from Hemantha Kulathilake (20)

NLP_KASHK:Parsing with Context-Free Grammar
NLP_KASHK:Parsing with Context-Free Grammar NLP_KASHK:Parsing with Context-Free Grammar
NLP_KASHK:Parsing with Context-Free Grammar
 
NLP_KASHK:Context-Free Grammar for English
NLP_KASHK:Context-Free Grammar for EnglishNLP_KASHK:Context-Free Grammar for English
NLP_KASHK:Context-Free Grammar for English
 
NLP_KASHK:POS Tagging
NLP_KASHK:POS TaggingNLP_KASHK:POS Tagging
NLP_KASHK:POS Tagging
 
NLP_KASHK:Markov Models
NLP_KASHK:Markov ModelsNLP_KASHK:Markov Models
NLP_KASHK:Markov Models
 
NLP_KASHK:Smoothing N-gram Models
NLP_KASHK:Smoothing N-gram ModelsNLP_KASHK:Smoothing N-gram Models
NLP_KASHK:Smoothing N-gram Models
 
NLP_KASHK:Evaluating Language Model
NLP_KASHK:Evaluating Language ModelNLP_KASHK:Evaluating Language Model
NLP_KASHK:Evaluating Language Model
 
NLP_KASHK:N-Grams
NLP_KASHK:N-GramsNLP_KASHK:N-Grams
NLP_KASHK:N-Grams
 
NLP_KASHK:Minimum Edit Distance
NLP_KASHK:Minimum Edit DistanceNLP_KASHK:Minimum Edit Distance
NLP_KASHK:Minimum Edit Distance
 
NLP_KASHK:Finite-State Morphological Parsing
NLP_KASHK:Finite-State Morphological ParsingNLP_KASHK:Finite-State Morphological Parsing
NLP_KASHK:Finite-State Morphological Parsing
 
NLP_KASHK:Morphology
NLP_KASHK:MorphologyNLP_KASHK:Morphology
NLP_KASHK:Morphology
 
NLP_KASHK:Text Normalization
NLP_KASHK:Text NormalizationNLP_KASHK:Text Normalization
NLP_KASHK:Text Normalization
 
NLP_KASHK:Finite-State Automata
NLP_KASHK:Finite-State AutomataNLP_KASHK:Finite-State Automata
NLP_KASHK:Finite-State Automata
 
NLP_KASHK:Regular Expressions
NLP_KASHK:Regular Expressions NLP_KASHK:Regular Expressions
NLP_KASHK:Regular Expressions
 
NLP_KASHK: Introduction
NLP_KASHK: Introduction NLP_KASHK: Introduction
NLP_KASHK: Introduction
 
COM1407: File Processing
COM1407: File Processing COM1407: File Processing
COM1407: File Processing
 
COm1407: Character & Strings
COm1407: Character & StringsCOm1407: Character & Strings
COm1407: Character & Strings
 
COM1407: Input/ Output Functions
COM1407: Input/ Output FunctionsCOM1407: Input/ Output Functions
COM1407: Input/ Output Functions
 
COM1407: Working with Pointers
COM1407: Working with PointersCOM1407: Working with Pointers
COM1407: Working with Pointers
 
COM1407: Arrays
COM1407: ArraysCOM1407: Arrays
COM1407: Arrays
 
COM1407: Program Control Structures – Repetition and Loops
COM1407: Program Control Structures – Repetition and Loops COM1407: Program Control Structures – Repetition and Loops
COM1407: Program Control Structures – Repetition and Loops
 

Recently uploaded

Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationAadityaSharma884161
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxsqpmdrvczh
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 

Recently uploaded (20)

9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint Presentation
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptx
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 

Structures, Unions & Dynamic Memory in C

  • 1. COM1407 Computer Programming Lecture 12 Structures, Unions & Dynamic Memory Allocation K.A.S.H. Kulathilake B.Sc. (Hons) IT, MCS , M.Phil., SEDA(UK) Rajarata University of Sri Lanka Department of Physical Sciences 1
  • 2. Objectives • At the end of this lecture students should be able to; ▫ Define, initialize and access to the C stuctuers. ▫ Develop programs using structures in arrays and functions. ▫ Use structures within structures and structures as pointers. ▫ Define, initialize and access to the C unions. ▫ Compare and contrast C structures and unions. ▫ Define memory allocation and de-allocation methods in C. ▫ Develop programs using memory allocation functions. ▫ Apply taught concepts for writing programs. 2
  • 3. Introduction • How do we keep the group of data items that are related but have different data types? • For example, suppose that along with the game scores, we want to store the name of each player, the country from which they come and their ages. • Here, the score is a float, the player and the country are character strings and the age is an integer. • We would like to store these four items together as one unit and to handle and process them together as a group. • In order to do this we can use structure data type. 3
  • 4. Defining a Structure • The keyword use to define structure data type is struct. • For our needs, we can define the structure as shown below. struct Participant { char Name[20]; char Country[25]; float Score; int Age; }; 4
  • 5. Defining a Structure (Cont…) • struct is a keyword and the Participant is a name or tag that we provided. • All that we are doing is defining a structure called struct Participant. • We are not creating a variable instead we are creating a new data type that includes or aggregate other C and C++ data types. • You can think of this as a structure template from which structure variables may be defined. • The order in which the structure members are defined is not important. 5
  • 6. Declaring Structure Variables • The following code shows how structure variables are declared. struct Participant Player1; Struct Participant Player2; or both together struct Participant Player1, Player1; 6
  • 8. Declaring Structure Variables (Cont…) struct date { int month; int day; int year; } todaysDate, purchaseDate; • Defines the structure date and also declares the variables todaysDate and purchaseDate to be of this type. 8
  • 9. Initializing Structure Variables • The following code shows how structure variables initialization. struct Participant Player1, Player2 = {"Korea", "Kenya", 4.6, 19}; 9
  • 10. Initializing Structure Variables (Cont…) 10 Player1 is defined and has four members. Player2 is also defined and its four members are initialized. Here, the order is important. They should be initialized in the same order that the structure members are defined as shown in the Figure. struct Participant Player1, Player2 = {"Korea", "Kenya", 4.6, 19};
  • 11. Initializing Structure Variables (Cont…) • You can also assign initial values to the variables in the normal fashion.Thus, struct date { int month; int day; int year; } todaysDate = { 1, 11, 2005 }; • Defines the structure date and the variable todaysDate with initial values as indicated. 11
  • 12. Accessing Values • With structures, we must follow the variable name by a period, followed by the member name to access one member. • This operator is known as member access operator (.). • For example, Player2.Score is equal to 4.60. 12
  • 13. Accessing Values (Cont…) #include <stdio.h> struct Participant { char Name[20]; char Country[25]; float Score; int Age; }; int main () { struct Participant Player1, Player2= {"Korea", "Kenya", 4.6, 19}; printf ("%sn", Player1.Name); printf ("%sn", Player2.Name); printf ("%in", Player2.Age); return 0; } 13 Player1 is not initialized. You do not get a value for this statement.
  • 14. Accessing Values (Cont…) #include <stdio.h> struct Participant { char Name[20]; char Country[25]; float Score; int Age; }; int main () { struct Participant Player1 = {"Sugath", "Sri Lanka",5.5, 20}; struct Participant Player2 = {"Korea", "Kenya", 4.6, 19}; printf ("%s : %sn", Player1.Name, Player1.Country); printf ("%s : %sn", Player2.Name, Player2.Country); return 0; } 14
  • 15. Point to Note in Structure Initialization #include <stdio.h> int main () { struct time { int hour; int min; int sec; }; struct time time1 = {12,10}; printf ("%in",time1.hour); printf ("%in",time1.min); printf ("%in",time1.sec); return 0; } 15 sets time1.hour to 12 and time1.minutes to 10 but gives no initial value to time1.seconds. In such a case, its default initial value is undefined.
  • 16. Exercise Write a program to store day, month and year into a structure. Print “Wish you a happy new year ” if both month and day of a particular day is equal to 1 16
  • 17. Exercise #include <stdio.h> struct Day { int year; int month; int day; }; int main () { struct Day today; today.month = 1; today.day = 1; today. year= 2017; if (today.month == 1 && today.day == 1) printf ("Wish you a happy new year"); return 0; } 17
  • 18. Using Structures in Expressions #include <stdio.h> int main (void) { struct date { int month; int day; int year; }; struct date today, tomorrow; const int daysPerMonth[12] = { 31, 28, 31, 30, 31, 30,31, 31, 30, 31, 30, 31 }; printf ("Enter today's date (mm dd yyyy): "); scanf ("%i%i%i", &today.month, &today.day, &today.year); 18
  • 19. Using Structures in Expressions (Cont…) if ( today.day == daysPerMonth[today.month - 1] && today.month !=12 ) { tomorrow.day = 1; tomorrow.month = today.month+1; tomorrow.year = today.year; } else if ( today.month == 12 && today.day == 31 ) { tomorrow.day = 1; tomorrow.month = 1; tomorrow.year = today.year + 1; } else { tomorrow.day = today.day+1; tomorrow.month = today.month; tomorrow.year = today.year; } printf ("Tomorrow's date is %i/%i/%.2i.n", tomorrow.month,tomorrow.day, tomorrow.year % 100); return 0; } 19
  • 20. Array of Structures • C does not limit you to storing simple data types inside an array; it is perfectly valid to define an array of structures. • For example, struct date birthdays[15]; • defines the array birthdays to contain 15 elements of type struct date. 20
  • 21. Array of Structures (Cont…) struct Participant Player[2]; • This will create an array called Player[ ] with only 2 slots, where each slot is a structure of type struct Participant. 21
  • 22. Array of Structures (Cont…) • Initializing Player array struct Participant Player[2]= { {"Korea", "Kenya", 4.6, 19}, {“Mary", "Australia", 4.8, 20} }; 22
  • 23. Array of Structures (Cont…) #include <stdio.h> struct Participant { char Name[20]; char Country[25]; float Score; int Age; }; int main () { struct Participant Player[2] = { {"Sugath", "Sri Lanka",5.5, 20}, {"Korea", "Kenya", 4.6, 19}}; printf ("%s : %sn", Player[0].Name, Player[0].Country); printf ("%s : %sn", Player[1].Name, Player[1].Country); return 0; } 23
  • 24. Array of Structures (Cont…) #include <stdio.h> int main () { struct time { int hour; int min; int sec; }; struct time runTime1 [5] ={ {12, 0, 0}, {12, 30, 0}, {13, 15, 0} }; printf ("%in",runTime1[0].hour); printf ("%in",runTime1[0].min); printf ("%in",runTime1[0].sec); return 0; } 24
  • 25. Structures Containing Structures • We can also create a structure based on other structures. • #include <stdio.h> struct Participant { char Name[20]; char Country[25]; float Score; int Age; }; struct Team { struct Participant captain; int wins; int losses; struct Participant member[2]; }; 25
  • 26. Structures Containing Structures (Cont…) int main() { struct Team slTeam = {{"Aravinda","LKR", 8.8,25}, 10, 2, { {"Kumara","LKR", 8.0,25}, {"Dilip","LKR", 7.8,25} } }; printf("Captain : %sn",slTeam.captain.Name); printf("Team Membersn"); printf("%sn", slTeam.member[0].Name); printf("%sn", slTeam.member[1].Name); printf("Match ScorenWins : %inLosses :%in", slTeam.wins, slTeam.losses); return 0; } 26
  • 27. Structures Containing Structures (Cont…) #include <stdio.h> struct date { int date; int month; int year; }; struct Employee { char ename[20]; int ssn; float salary; struct date doj; }emp = {"Pritesh",1000,1000.50,{22,6,1990}}; 27
  • 28. Structures Containing Structures (Cont…) int main(int argc, char *argv[]) { printf("nEmployee Name : %s",emp.ename); printf("nEmployee SSN : %d",emp.ssn); printf("nEmployee Salary : %f",emp.salary); printf("nEmployee DOJ : %d/%d/%d", emp.doj.date,emp.doj.month,emp.doj.year); return 0; } 28
  • 29. Structures Containing Structures (Cont…) int main() { struct Team team1 ={ {"Jasmine", "Cambodia", 3.5, 22}, 5, 2, {{"Michael", "Cambodia", 5.2, 20}, {"Leonard", "Cambodia", 4.0, 24}} }; printf ("%sn", team1.Captain.Name); printf ("%sn", team1.Player[0].Country); return 0; } 29
  • 30. Functions & Structures #include <stdio.h> #include <string.h> struct Mobile { char Make[20]; int Year; }; struct Mobile FindYear(char Name[ ]); void PrintOldest(struct Mobile Auto1, struct Mobile Auto2); 30
  • 31. Functions & Structures (Cont…) struct Mobile FindYear(char Name[]) { struct Mobile Car; printf("What year is the %s? ", Name); scanf("%d", &Car.Year); printf("Car.Year = %dn", Car.Year); strcpy(Car.Make, Name); return Car; } 31
  • 32. Functions & Structures (Cont…) void PrintOldest(struct Mobile Auto1, struct Mobile Auto2) { if(Auto1.Year < Auto2.Year) printf("The oldest car is the %sn", Auto1.Make); else if(Auto1.Year > Auto2.Year) printf("The oldest car is the %sn", Auto2.Make); else printf("They are both the same age!n"); } 32
  • 33. Functions & Structures (Cont…) int main() { struct Mobile Car1, Car2; Car1 = FindYear("Toyota"); Car2 = FindYear("Nissan"); PrintOldest(Car1, Car2); return 0; } 33
  • 34. Pointers to Structures • You can define pointers to structures in the same way as you define pointer to any other variable: struct Books *struct_pointer; • Now, you can store the address of a structure variable in the above defined pointer variable. • To find the address of a structure variable, place the '&'; operator before the structure's name as follows: struct_pointer = &Book1; • To access the members of a structure using a pointer to that structure, you must use the → operator as follows: struct_pointer->title; 34
  • 35. Pointers to Structures (Cont…) #include <stdio.h> #include <string.h> struct Books { char title[50]; char author[50]; char subject[100]; int book_id; }; /* function declaration */ void printBook( struct Books *book ); 35
  • 36. Pointers to Structures (Cont…) int main( ) { struct Books Book1;/*Declare Book1 of type Book*/ struct Books Book2;/*Declare Book2 of type Book*/ /* book 1 specification */ strcpy( Book1.title, "C Programming"); strcpy( Book1.author, "Nuha Ali"); strcpy( Book1.subject, "C Programming Tutorial"); Book1.book_id = 6495407; 36
  • 37. Pointers to Structures (Cont…) /* book 2 specification */ strcpy( Book2.title, "Telecom Billing"); strcpy( Book2.author, "Zara Ali"); strcpy( Book2.subject, "Telecom Billing Tutorial"); Book2.book_id = 6495700; /* print Book1 info by passing address of Book1 */ printBook( &Book1 ); /* print Book2 info by passing address of Book2 */ printBook( &Book2 ); return 0; } 37
  • 38. Pointers to Structures (Cont…) void printBook( struct Books *book ) { printf( "Book title : %sn", book->title); printf( "Book author : %sn", book->author); printf( "Book subject : %sn", book->subject); printf( "Book book_id : %dn", book->book_id); } 38
  • 39. Union • A union is a block of memory that is used to hold data items of different types. • In C, a union is similar to a structure, except that the data items saved in the union are overlaid in order to share the same memory location. • That is, they all share the same starting address, unlike a structure where each member gets its own area of memory. • 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-purpose. 39
  • 40. Defining a Union • To define a union, you must use the union statement in the same way as you did while defining a structure. • The union statement defines a new data type with more than one member for your program. • At the end of the union's definition, before the final semicolon, you can specify one or more union variables but it is optional. union Data { int i; float f; char str[20]; } data; 40
  • 41. Defining a Union (Cont…) • Now, a variable of Data type can store an integer, a floating-point number, or a string of characters. • It means a single variable, i.e., same memory location, can be used to store multiple types of data. • You can use any built-in or user defined data types inside a union based on your requirement. • The memory occupied by a union will be large enough to hold the largest member of the union. • For example, in the above example, Data type will occupy 20 bytes of memory space because this is the maximum space which can be occupied by a character string. 41
  • 42. Defining a Union (Cont…) #include <stdio.h> union Data { int i; float f; char str[20]; }; int main( ) { union Data data; printf( "Memory size occupied by data : %dn", sizeof(data)); return 0; } 42
  • 43. Accessing Union Members #include <stdio.h> #include <string.h> union Data { int i; float f; char str[20]; }data; int main( ) { data.i = 10; data.f = 220.5; strcpy( data.str, "C Programming"); printf( "data.i : %in", data.i); printf( "data.f : %fn", data.f); printf( "data.str : %sn", data.str); return 0; } 43 To access any member of a union, we use the member access operator (.). Here, we can see that the values of i and f members of union got corrupted because the final value assigned to the variable has occupied the memory location and this is the reason that the value of str member is getting printed very well.
  • 44. Accessing Union Members (Cont…) #include <stdio.h> #include <string.h> union Data { int i; float f; char str[20]; }; int main( ) { union Data data; data.i = 10; printf( "data.i : %dn", data.i); data.f = 220.5; printf( "data.f : %fn", data.f); strcpy( data.str, "C Programming"); printf( "data.str : %sn", data.str); return 0; } 44
  • 45. Memory Allocation • In C, the exact size of array is unknown until compile time, i.e., the time when a compiler compiles your code into a computer understandable language. • So, sometimes the size of the array can be insufficient or more than required. • Dynamic memory allocation allows your program to obtain more memory space while running, or to release it if it's not required. • In simple terms, Dynamic memory allocation allows you to manually handle memory space for your program. 45
  • 46. Memory Allocation (Cont…) • Although, C language inherently does not have any technique to allocate memory dynamically, there are 4 library functions under "stdlib.h" for dynamic memory allocation. 46 Function Use of Function malloc() Allocates requested size of bytes and returns a pointer first byte of allocated space calloc() Allocates space for an array elements, initializes to zero and then returns a pointer to memory free() deallocate the previously allocated space realloc() Change the size of previously allocated space
  • 47. C malloc() • The name malloc stands for "memory allocation". • The function malloc() reserves a block of memory of specified size and return a pointer of type void which can be casted into pointer of any form. ptr = (cast-type*) malloc(byte-size) • Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory with size of byte size. If the space is insufficient, allocation fails and returns NULL pointer. ptr = (int*) malloc(100 * sizeof(int)); • This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively and the pointer points to the address of first byte of memory. 47
  • 48. C calloc() • The name calloc stands for "contiguous allocation". • The only difference between malloc() and calloc() is that, malloc() allocates single block of memory whereas calloc() allocates multiple blocks of memory each of same size and sets all bytes to zero. ptr = (cast-type*)calloc(n, element-size); • This statement will allocate contiguous space in memory for an array of n elements. For example: ptr = (float*) calloc(25, sizeof(float)); • This statement allocates contiguous space in memory for an array of 25 elements each of size of float, i.e, 4 bytes. 48
  • 49. C free() • Dynamically allocated memory created with either calloc() or malloc() doesn't get freed on its own. • You must explicitly use free() to release the space. free(ptr); • This statement frees the space allocated in the memory pointed by ptr. 49
  • 50. Exercise Write a C program to find sum of n elements entered by user. To perform this program, allocate memory dynamically using malloc() function. 50
  • 51. Exercise #include <stdio.h> #include <stdlib.h> int main() { int num, i, *ptr, sum = 0; printf("Enter number of elements: "); scanf("%d", &num); ptr = (int*) malloc(num * sizeof(int)); if(ptr == NULL) { printf("Error! memory not allocated."); exit(0); } 51
  • 52. Exercise printf("Enter elements of array: "); for(i = 0; i < num; ++i) { scanf("%d", ptr + i); sum += *(ptr + i); } printf("Sum = %d", sum); free(ptr); return 0; } 52
  • 53. Exercise Write a C program to find sum of n elements entered by user. To perform this program, allocate memory dynamically using calloc() function. 53
  • 54. Exercise #include <stdio.h> #include <stdlib.h> int main() { int num, i, *ptr, sum = 0; printf("Enter number of elements: "); scanf("%d", &num); ptr = (int*) calloc(num, sizeof(int)); if(ptr == NULL) { printf("Error! memory not allocated."); exit(0); } 54
  • 55. Exercise printf("Enter elements of array: "); for(i = 0; i < num; ++i) { scanf("%d", ptr + i); sum += *(ptr + i); } printf("Sum = %d", sum); free(ptr); return 0; } 55
  • 56. C realloc() • If the previously allocated memory is insufficient or more than required, you can change the previously allocated memory size using realloc(). ptr = realloc(ptr, newsize); • Here, ptr is reallocated with size of newsize. 56
  • 57. Exercise #include <stdio.h> #include <stdlib.h> int main() { int *ptr, i , n1, n2; printf("Enter size of array: "); scanf("%d", &n1); ptr = (int*) malloc(n1 * sizeof(int)); printf("Address of previously allocated memory: "); 57
  • 58. Exercise for(i = 0; i < n1; ++i) printf("%ut",ptr + i); printf("nEnter new size of array: "); scanf("%d", &n2); ptr = realloc(ptr, n2); for(i = 0; i < n2; ++i) printf("%ut", ptr + i); return 0; } 58
  • 59. Exercise Find Largest Element Using Dynamic Memory Allocation - calloc(). 59
  • 60. Exercise #include <stdio.h> #include <stdlib.h> int main() { int i, num; float *data; printf("Enter total number of elements(1 to 100): "); scanf("%d", &num); data = (float*) calloc(num, sizeof(float)); if(data == NULL) { printf("Error!!! memory not allocated."); exit(0); } 60
  • 61. Exercise printf("n"); for(i = 0; i < num; ++i) { printf("Enter Number %d: ", i + 1); scanf("%f", data + i); } for(i = 1; i < num; ++i) { if(*data < *(data + i)) *data = *(data + i); } printf("Largest element = %.2f", *data); return 0; } 61
  • 62. Objective Re-cap • Now you should be able to: ▫ Define, initialize and access to the C stuctuers. ▫ Develop programs using structures in arrays and functions. ▫ Use structures within structures and structures as pointers. ▫ Define, initialize and access to the C unions. ▫ Compare and contrast C structures and unions. ▫ Define memory allocation and de-allocation methods in C. ▫ Develop programs using memory allocation functions. ▫ Apply taught concepts for writing programs. 62
  • 63. References • Chapter 09 - Programming in C, 3rd Edition, Stephen G. Kochan 63
  • 64. Next: Character & Strings 64