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.
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.
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
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
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
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
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
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
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