Professional Documents
Culture Documents
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
1
Contents
Structures
Unions
Enumerations
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
2
ADT
Why have them?
Allows for easier definition of objects
Closer resemblance with real world
Can group related attributes together to represent one entity.
Define return types for functions with multiple values
What needs are there?
one type, represented by a related set of data elements
(struct)
one type, can attain one state out of various sets of data
elements (union)
one type, useful for logically related constant integers(enum)
Examples!!!
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
3
Structures (struct)
Arrays require that all elements be of the same data type.
Many times it is necessary to group information of different data
types.
An example is a materials list for a product.
The list typically includes a name for each item, a part number,
dimensions, weight, and cost all of different data types
C and C++ support data structures that can store combinations
of character, integer floating point and enumerated type
data. They are called a structs.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
4
Structures (Contd.)
Way to package primitive data objects into an
aggregate data object
Collections of related variables (components) under
one name
Can contain variables of different data types
U1.
5
Syntax
Syntax
struct structure_name {
type1 member1;
type2 member2;
};
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
6
Structure - Definition
Example
struct
struct point
point {{
int
int x;
x;
int
int y;
y;
double
double dist;
dist; /*
/* from
from origin
origin */
*/
};
/*
MUST
have
semicolon!
*/
}; /* MUST have semicolon! */
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
7
Structure - Definition
Another Example
struct card {
char *face;
char *suit;
};
U1.
8
Thus
A struct is a derived data type.
Is composed of members that are each fundamental
or derived data types.
A single struct would store the data for one object.
An array of structs would store the data for
several objects
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
9
Structure Definition - II
A struct cannot contain an instance of itself
but can contain a member that is a pointer to the
same structure type
A structure definition does not create a
variable in memory
Instead creates a new data type used to define
structure variables
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
10
Definitions
Defined like other variables (note the subtle
difference):
struct card oneCard,
deck[52],
*cPtr;
U1.
11
Structure Definitions
Valid Operations
1. Assigning a structure to a structure of the same type
2. Taking the address (&) of a structure
3. Accessing the members of a structure
4. Using the sizeof operator to determine the size of a
structure
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
12
Initializing Structures
Examples
struct point pointA= {10, 20};
struct card oneCard = { "Three", "Hearts" };
struct point pointB= pointA;
struct card threeHearts = oneCard; //caution
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
13
Assigning Values
struct point pointB;
pointB.x = 23;
pointB.y = 40;
What about the card struct!!!.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
14
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
15
To Do
Declare two structure variables pointA and
pointB.
Write a code segment to
Accept the coordinates of the points from the
user
calculate and display the distance between the
two points
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
16
U1.
17
typedef
Creates synonyms (aliases) for previously defined data types
Use typedef to create shorter type names
Example: typedef struct Card* CardPtr;
Defines a new type name CardPtr as a synonym for type
struct Card *
typedef does not create a new data type
Writing typedef struct card card; eliminates the
need of using the struct keyword while declaring variables.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
18
typedef - II
Type component of typedef can also be a struct
typedef struct {
int x;
int y;
double dist;
} Point;
Point p1, p2;
/* no "struct" */
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
19
TO Do
Write a function that
accepts two parameters of type struct point
calculates and returns the distance between the two
points.
The declaration of the function will be---
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
20
Arrays of Structures
#define
#define MAX_STUDENT
MAX_STUDENT 100
100
typedef
typedef struct
struct {{ /*
/* define
define aa new
new type
type */
*/
char
char name[80];
name[80];
int
int name_len;`
name_len;`
int
int student_number;
student_number;
}} student;
student;
/*
/* create
create list
list of
of elements
elements of
of type
type student
student */
*/
student
student class[MAX_STUDENT];
class[MAX_STUDENT];
for
for (i
(i == 0;
0; ii << MAX_STUDENT;
MAX_STUDENT; i++)
i++) {{
gets
gets (class[i].name);
(class[i].name);
class[i].name_len
class[i].name_len == strlen
strlen (class[i].name);
(class[i].name);
}}
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
21
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
22
// declaration
Actions:
Each array element is a pointer to a structure
Refer to array elements: res[i]
Allocate memory:
res[i]= (Student*) malloc (sizeof(Student));
Refer to data members of Result variable stored at ith location
res[i]->Roll
res[i]->Marks[i]
Pros & Cons
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
23
U1.
24
U1.
25
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
26
Print dob:
printf (%d/%d/%d,
p.dob.dd, p.dob.mm, p.dob.yy);
U1.
27
Print address:
scanf (%d, p.address->HouseNo);
printf (%s, p.address->Country);
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
28
E
rear
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
29
Rules:
a structure cannot refer to its own name before it is
defined.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
30
10
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
31
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
32
Sample Definition - I
struct
struct Employee
Employee
{{
name
name char[30];
char[30];
char
char gender
gender ;; /*
/* (M)ale,
(M)ale, (F)emale
(F)emale */
*/
char
/*
char type;
type;
/* (T)emporary,
(T)emporary, (P)ermanent
(P)ermanent */
*/
char
char maritalStatus;
maritalStatus; /*
/* (S)ingle,
(S)ingle, (M)arried,
(M)arried,
(D)ivorced
(D)ivorced */
*/
};
};
sizeof
sizeof(struct
(structEmployee)
Employee)!!!
!!!
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
33
11
Sample Definition - II
struct
struct Employee
Employee
{{
name
name char[30];
char[30];
char
char gender:1;
gender:1; /*
/* (M)ale,
(M)ale, (F)emale
(F)emale */
*/
char
char type:1;
type:1; /*
/* (T)emporary,
(T)emporary, (P)ermanent
(P)ermanent */
*/
char
char maritalStatus:2;
maritalStatus:2; /*
/* (S)ingle,
(S)ingle,
(M)arried,
(M)arried, (D)ivorced
(D)ivorced */
*/
};
};
sizeof
sizeof(struct
(structEmployee)
Employee)!!!
!!!
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
34
Memory Map
Sample Definition:
I
Sample Definition: II
gender
gender
type
type
maritalStatus
maritalStatus
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
35
UNIONS
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
36
12
union
Like struct; union is also an ADT
struct
Stores a set of variables
Various variables (members) stored at contiguous
memory locations
union
Gives a choice of storing one variable out of a set
Allows the same memory location to be treated as
different variables at different instances of time
Used while storing related but mutually exclusive data
elements.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
37
Example
Problem Statement
You have to store results for a set of exams.
Given, few of the papers are compulsory and the
rest are electives
The compulsory papers are marked (0-100,
fractions allowed)
The electives are graded (A-F)
As a given paper can either be compulsory or
elective, reserving space for both would lead to
wastage of memory.
Solution:
union!!!
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
38
General Usage
Store a flag & a union in a struct
Use the flag to indicate what should the memory
locations be interpreted as!!!
As different variables share the same memory
space;
The size of a union variable is always large enough to
accommodate the largest of the possible components
Writing into one variable will overwrite all other
members
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
39
13
struct
struct Result
Result
{{
char
char rollNo[10];
rollNo[10];
char
char paperCode[6];
paperCode[6];
union
union Status
Status status;
status;
}} ;;
struct
struct Paper
Paper
{{
char
char paperCode[6];
paperCode[6];
char
char name
name [30]
[30] ;;
char
char type;
type; //
// CC or
or OO
}} ;;
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
40
Enumerations
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
41
Enumeration
Enumeration is a means of defining a set of integer
constants.
It is defined using the keyword enum and the syntax is:
enum tag_name {name_0, , name_n} ;
The tag_name is not used directly.
The names in the braces are symbolic constants that take
on integer values from zero through n.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
42
14
Enumeration: example
E.g.:
enum colors { red, yellow, green } ;
Creates three constants.
red is assigned the value 0,
yellow is assigned 1;and
green is assigned 2.
The values associated with the constants can be controlled
if required.
Unless specified explicitly, each symbol is given a value that
is one greater that the preceding one.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
43
Enumeration: Example
enum colors { red, yellow=5, green } ;
Creates three constants.
red is assigned the value 0,
yellow is assigned 5;and
green is assigned 6.
enum colors { red=-1, yellow=5, green } ;
enum colors { red=-1, yellow=5, green=0 } ;
enum colors { red, yellow, green=90 } ;
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
44
Using enum
You can declare and name a finite set, for example
enum day {sun, mon, tue, wed, thu, fri, sat};
and then use these as variable types & reference values.
The individual values are const int; default is {0, 1, 2...},
but can be changed.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
45
15
Using enum
Declaring variables: enum day d1, d2;
Using: if (d1 != d2) { /* do something... */ }
Declaring variables along with the template:
enum outcome {win, lose, tie, error} a, b, c;
Note: The data-type, here is enum day;
Using typedef:
typedef
enum day
day;
U1.
46
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
enum: Example
/*
/* Using
Using enum
enum to
to access
access array
array elements*/
elements*/
#include
#include <stdio.h>
<stdio.h>
int
main(
)
int main( )
{{
int
int March[5][7]={{0,0,1,2,3,4,5},{6,7,8,9,10,11,12},
March[5][7]={{0,0,1,2,3,4,5},{6,7,8,9,10,11,12},
{13,14,15,16,17,18,19},
{13,14,15,16,17,18,19}, {20,21,22,23,24,25,26},
{20,21,22,23,24,25,26},
{27,28,29,30,31,0,0}};
{27,28,29,30,31,0,0}};
enum
enum days
days {Sun,
{Sun, Mon,
Mon, Tue,
Tue, Wed,
Wed, Thu,
Thu, Fri,
Fri, Sat};
Sat};
enum
enum weeks
weeks {WeekOne,
{WeekOne, WeekTwo,
WeekTwo, WeekThree,
WeekThree, WeekFour,
WeekFour,
WeekFive};
WeekFive};
printf
printf ("Monday
("Monday the
the third
third week
week of
of
%d\n",
%d\n", March
March [WeekThree]
[WeekThree] [Monday]
[Monday]
}}
March
March is
is March
March
);
);
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
47
Function Pointers
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
48
16
Function Pointers
Pointers to functions
Contain address of function
The way name of an array is address of its first
element
Function name is starting address of code that
defines function
Passed to functions
Returned from functions
Stored in arrays
Assigned to other function pointers
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
49
Function Pointers
Calling functions using pointers
The declaration:
bool ( *compare ) ( int, int );
OR
Use the normal syntax
compare( int1, int2 )
Could be confusing
Appears like compare is the name of actual function in the program
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
50
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
51
17
Example
void
void function1(
function1( int
int );
);
void
void function2(
function2( int
int );
);
void
void function3(
function3( int
int );
);
int
int main()
main()
{{
//initialize
//initialize array
array of
of 33 pointers
pointers to
to functions
functions
//
// each
each takes
takes an
an int
int argument
argument and
and returns
returns void
void
int
int choice;
choice;
void
(*f[
3
])(
int
)
=
void (*f[ 3 ])( int ) =
{{ function1,
function1, function2,
function2, function3
function3 };
};
do{
do{
printf
("Enter
a
number
between
0
and
2,
3
to
end:
printf ("Enter a number between 0 and 2, 3 to end: );
);
scanf
scanf (%d,
(%d, &choice);
&choice);
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
52
Usage
//
// invoke
invoke function
function at
at location
location choice
choice in
in
array
array ff
//
// and
and pass
pass choice
choice as
as an
an argument
argument
(*f[
choice
])(
choice
(*f[ choice ])( choice );
);
}while(choice!=3);
}while(choice!=3);
printf
printf ("Program
("Program execution
execution completed.\n);
completed.\n);
return
return 0;
0; //
// indicates
indicates successful
successful
termination
termination
}//
}// end
end main
main
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
53
Usage
void
void function0(
function0( int
int aa ))
{{
printf
printf (from
(from function0;
function0; input
input data
data %d\n\n,
%d\n\n, a)
a) ;;
}} //
// end
end function0
function0
void
void function1
function1 (( int
int aa ))
{{
printf
printf (from
(from function1;
function1; input
input data
data %d\n\n,
%d\n\n, a)
a) ;;
}} //
// end
end function1
function1
void
void function2(
function2( int
int aa ))
{{
printf
printf (from
(from function2;
function2; input
input data
data %d\n\n,
%d\n\n, a)
a) ;;
}} //
// end
end function2
function2
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
54
18
Exercise
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
55
Shalini
Singh Jaspal,
Lecturer,
BVICAM
Bharati
Vidyapeeths
Institute
of Computer
Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
56
56
Revision
Pointers
Store address.
Provide a means of accessing a memory location
Array
Array name
name can
canbe
be said
said to
to be
be aa pointer
pointer to
to its
its
00thth element!!!
element!!!
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
57
19
Pointer Arithmetic
A subset of arithmetic operations can be applied to pointers.
These operations have significant applications in array
processing.
Operations Allowed
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
58
Incrementing Integers
int i=100;
100
0xFA10
i++;
101
0xFA10
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
59
Incrementing Pointers
FA10
0xF100
p
p++;
FA12
0xF100
U1.
60
20
Here n is the size of a variable having the same datatype as that of the pointer.
This operation is of little use when dealing with simple variables
But can be used to process arrays efficiently. How!!!
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
61
p
F000
arr
0xFA00
10
20
30
40
50
0xF000
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
62
20
30
40
50
0xF000
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
63
21
20
30
40
50
0xF000
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
64
No
Legal
t le
ga
Array
Arraynames
namesare
areconst
const
pointers
pointers
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
65
for
for (i=0;
(i=0; i<MAX;
i<MAX; i++)
i++)
scanf
scanf (%d,
(%d, ------------- );
);
}}
th
Address
Addressof
ofiithelement
elementusing
using
pointer
pointernotation
notation
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
66
22
th
Value
Valueof
ofiithelement
elementusing
usingpointer
pointer
notation
notation
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
67
*(arr[i] + j) arr[i][j]
*(
*(*(arr
*(arr++i)i)++jj))
arr[i][j]
arr[i][j]
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
68
30
40
10
10
20
10
15
10
60
15
0
10
50
10
20
30
70
10
56
10
60
20
40
12
arr[i][j][k]
arr[i][j][k]
*(
*(*(
*(*(arr
*(arr++ii))++j)j) ++k)
k)
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
69
23
10 20 30 40 45 35 55 75 23 40 67 10
1st 1D array
2nd 1D array
3rd 1D array
U1.
70
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
71
Subtraction - Pointers
Subtracting a pointer (p1) from another (p2) : p1-p2
Gives an integer.
Makes sense only if p1 & p2 contain addresses of elements of the
same array.
Tells how many data elements can be accommodated between the
address locations represented by p1 & p2.
What
Whatififp1
p1<<p2
p2??
What
Whatififp1
p1&
&p2
p2dont
dontpoint
pointto
toelements
elementsof
ofsame
samearray
array??
What
Whatififdata
datatype
typeof
ofp1
p1&
&p2
p2isisdifferent
differentfrom
fromthat
thatof
ofthe
thearray
array??
What
Whatififdata
datatype
typeof
ofp1
p1isisdifferent
differentfrom
fromthat
thatof
ofp2
p2??
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
72
24
Comparison Pointers
Comparison operators when applied on pointers
Evaluate to true (1) or false (0)
Used to test whether the address location stored in one pointer
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
73
* and ++
*p++ means:
*p++
find the value at the end of the pointer
*p++
increment the POINTER to point to the next element
*++p means:
*++p
increment the pointer
*++p
find the value at the end of the pointer
(*p)++ means:
(*p)++ find the value at the end of the pointer
(*p)++ increment the VALUE AT THE END OF THE POINTER
U1.
74
const Pointers
Two memory locations can be accessed using a
pointer
The pointer variable itself
The variable stored at the address contained in the
pointer variable
q
int
int
int
int
q=10;
q=10;
*p=
*p= &q;
&q;
10
0xF100
p
0xFA00
F100
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
75
25
const Pointers II
The const keyword can be associated with either of the two locations
accessible via the pointer.
int const *p;
*p is being declared to be a constant
*p=20; is illegal
int * const p;
p is being declared to be a constant
p=&i; is illegal
int const * const p;
--------------------------------
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
76
void Pointer
Pointer must always have a type that they point to. Exception:
void * is a generic pointer, and can be assigned to any variable type.
However, for good practice you should always type cast it into the
appropriate pointer type.
Example:
int
void
*p;
*v;
Used
Used by
by expert
expert programmers
programmers for
for
accessing
accessingpure
pureaddresses
addresses
Used
Usedin
indynamic
dynamicallocation
allocationof
ofmemory
memory
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
77
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
78
26
U1.
79
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
80
U1.
81
27
Releasing Memory
void free (void *);
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
82
malloc
Header File: stdlib.h
Return Type: A void* pointer to the first byte in the sequence
Return Value:
On Success: void* pointer holding the address of the chunk of
memory that was allocated
On Failure: NULL
Parameter: The number of bytes to allocate
Problems
need to calculate the number of bytes
need to convert the void* pointer to a pointer of type actually
required (eg, int*, char*)
need to initialize the memory cells thus received.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
83
calloc
Header File: stdlib.h
Return Type: A void* pointer to the first byte in the sequence
Return Value:
On Success: void* pointer holding the starting address of the
chunk of memory that was allocated
On Failure: NULL
Parameter:
1.The number of objects for which memory is to be allocated
2.Size of each such item.
calloc allocates a block of size (numObjects * objSize) and clears it to 0
Problems
need to convert the void* pointer to a pointer of type actually
required (eg, int*, char*)
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
84
28
realloc
Header File: stdlib.h
Return Type: A void* pointer to the first byte in the sequence
Return Value:
On Success: void* pointer holding the starting address of the
reallocated block
On Failure: NULL
Parameter:
1. Staring address of the old block.
2. New size to be allocated.
Action
Adjusts the size of the block to new size
Block is copied to a new location if necessary.
Problems
need to convert the void* pointer to the required type.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
85
Releasing Memory
Programs which allocate storage space dynamically often do not need
it for the entire run
It is important to release memory once it is no longer required
The standard library function free provides this facility of releasing the
memory pointed to by p
p should point to an area of storage previously allocated by malloc,
calloc or realloc
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
86
free
Declaration
void free( void *p);
Header File: stdlib.h
Parameter:
pointer of type void*
Any pointer type used will be automatically cast
Action:
Releases a memory block that was allocate dynamically
Syntax: free(ptr);
Technically, this is: free((void*) ptr);
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
87
29
Memory management
malloc() and free() must be used carefully to avoid bugs
Potential problems
dangling pointers
memory leaks
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
88
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
89
NULL pointers
Standard headers contain the following macro
#define NULL 0
NULL is used with pointers to indicate that a pointer is
not pointing to anything
We can then use it in a statement like
if (x==NULL) {
x = (int*) malloc(10*sizeof(x));
}
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
90
30
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
91
Summary
Steps for using dynamic arrays:
Declare a pointer corresponding to the desired type of the array elements.
Initialize the pointer via a memory allocation function (calloc /
malloc).
Check the returned pointer against NULL.
Increase or decrease the number of elements by calling the realloc
function.
Release the storage by calling free.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
92
}}
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
93
31
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
94
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
95
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
96
32
Try it yourself
-- extend the concept of 2D array
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
97
U1.
98
1.
1.
2.
2.
3.
3.
What
Whatisisflattened
flattenedarray
arrayapproach?
approach?
Which
Whichof
ofthese
thesecan
canbe
beused
usedfor
fordynamic
dynamicarray
arrayint
int**a?
**a?
What
Whatisisaapointer
pointerto
toan
anarray?
array?
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
99
33
Pointer to an Array
Given a 2D array
int arr[5][10]
arr &arr[0]
But, arr[0] is an array
Thus, arr becomes a pointer to an array
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
100
Pointer to an Array
Declaring a pointer to an array:
int (*ptr) [MAX];
Here, ptr is a pointer to a 1D array containing MAX
elements
The statement, ptr= arr; makes ptr point to arr[0]
Now, ptr can be used to process arr.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
101
int
int data
data [MAXROW][MAXCOL];
[MAXROW][MAXCOL];
f4
f4 (data);
(data);
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
102
34
void
void
void
void
f1
f2
f3
f4
(int
(int
(int
(int
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
103
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
104
//a is a 2D array
//a is a 2D array
Try yourself
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
105
35
U1.
106
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
107
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
Array of Pointers
int * arr [MAX];
Here, arr is an array of MAX variables.
Each element of the array is an integer pointer.
Thus, each element can be made to point to any integer / set of integers.
F200
FA10
i
Dynamically
allocated
memory
100
0xFA10
arr
10
20
30
40
50
0xF000
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
108
36
20
F052
10
20
F100
FA00
10
FA80
30
40
50
25
45
532
20
45
NULL
F990
150
Create
Createragged
raggedarray,
array,
Fixed
Fixednumber
numberof
ofrows,
rows,
Variable
Variablenumber
numberof
ofcolumns
columns
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
109
p
F000
0xFA00
10
20
30
40
50
25
35
50
10
22
31
23
12
34
29
30
41
70
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
110
return
Can give a NULL
return 0;
0;
}}
pointer exception
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
111
37
return
0;
return 0;
}}
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
112
Function Pointers
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
113
Function Pointers
Pointers to functions
Contain address of function
The way name of an array is address of its first
element
Function name is starting address of code that
defines function
Passed to functions
Returned from functions
Stored in arrays
Assigned to other function pointers
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
114
38
Function Pointers
Calling functions using pointers
The declaration:
bool ( *compare ) ( int, int );
OR
Use the normal syntax
compare( int1, int2 )
Could be confusing
Appears like compare is the name of actual function in the program
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
115
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
116
Example
void
void function1(
function1( int
int );
);
void
void function2(
function2( int
int );
);
void
void function3(
function3( int
int );
);
int
int main()
main()
{{
//initialize
//initialize array
array of
of 33 pointers
pointers to
to functions
functions
//
// each
each takes
takes an
an int
int argument
argument and
and returns
returns void
void
int
int choice;
choice;
void
void (*f[
(*f[ 33 ])(
])( int
int )) ==
{{ function1,
function1, function2,
function2, function3
function3 };
};
do{
do{
printf
printf ("Enter
("Enter aa number
number between
between 00 and
and 2,
2, 33 to
to end:
end: );
);
scanf
scanf (%d,
(%d, &choice);
&choice);
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
117
39
Usage
//
// invoke
invoke function
function at
at location
location choice
choice in
in
array
array ff
//
// and
and pass
pass choice
choice as
as an
an argument
argument
(*f[
choice
])(
choice
(*f[ choice ])( choice );
);
}while(choice!=3);
}while(choice!=3);
printf
printf ("Program
("Program execution
execution completed.\n);
completed.\n);
return
0;
//
indicates
return 0; // indicates successful
successful
termination
termination
}//
}// end
end main
main
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
118
Usage
void
void function0(
function0( int
int aa ))
{{
printf
printf (from
(from function0;
function0; input
input data
data %d\n\n,
%d\n\n, a)
a) ;;
}} //
// end
end function0
function0
void
void function1
function1 (( int
int aa ))
{{
printf
printf (from
(from function1;
function1; input
input data
data %d\n\n,
%d\n\n, a)
a) ;;
}} //
// end
end function1
function1
void
void function2(
function2( int
int aa ))
{{
printf
printf (from
(from function2;
function2; input
input data
data %d\n\n,
%d\n\n, a)
a) ;;
}} //
// end
end function2
function2
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
119
Exercise
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Shalini Singh Jaspal
U1.
120
40