SlideShare a Scribd company logo
UNIT II : DMA, Pointers and Functions,
Pointers and Structures
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Perundurai, Erode, Tamilnadu, India
Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018.
20CST21 – Programming and Linear Data Structures
Syllabus – Unit Wise
5/12/2021 2.1 _ Dynamic Memory Allocation 2
List of Exercises
5/12/2021 2.1 _ Dynamic Memory Allocation 3
Text Book and Reference Book
5/12/2021 2.1 _ Dynamic Memory Allocation 4
Unit I : Contents
1. Dynamic Memory Allocation
2. Function pointers
3. Calling a function using a function pointer
4. Structures – Introduction
5. Structures in Functions
6. Pointers to structures
7. Accessing structure members
8. Using pointer as a function argument
9. Array of structures
10. Self referential structures.
5/12/2021 5
2.1 _ Dynamic Memory Allocation
Dynamic Memory Allocation
• While programming, if we know the amount
of memory required prior, then we can
allocate memory in advance during compile
time itself.
• For example, to store a name of any
employee whose name may go up to a
maximum of 50 characters, we can define it
using array as follows:
5/12/2021 2.1 _ Dynamic Memory Allocation 6
Dynamic Memory Allocation
• But there might be a situation when we have to
allocate memory based on the user requirement i.e.,
amount of memory needed may change over time.
• For example, Let us consider a situation where we have
no idea about the length of the text like detailed
description about a topic.
• Here we need to define a pointer to character without
defining how much memory is required and later,
based on the requirement, we can allocate memory
during execution time.
• The process of allocating memory during program
execution is called dynamic memory allocation.
5/12/2021 2.1 _ Dynamic Memory Allocation 7
Difference between static memory allocation
and dynamic memory allocation
5/12/2021 2.1 _ Dynamic Memory Allocation 8
Dynamic memory allocation functions
• The C language offers the following dynamic
memory allocation functions in stdlib.h
header file.
5/12/2021 2.1 _ Dynamic Memory Allocation 9
malloc() function
• “malloc” or “memory allocation”
• malloc () function is used to allocate space in memory
during the execution of the program.
• malloc() allocates memory block of given size (in
bytes) and returns a pointer to the beginning of the
block.
• It returns a pointer of type void which can be cast into
a pointer of any form.
• The malloc() function allocates single block of
requested memory.
• It does not initialize memory at execution time, so the
allocated memory is filled with some garbage value.
• It returns NULL if sufficient memory is not allocated.
5/12/2021 2.1 _ Dynamic Memory Allocation 10
malloc() function
• The syntax of malloc() function is given below:
5/12/2021 2.1 _ Dynamic Memory Allocation 11
malloc() function
5/12/2021 2.1 _ Dynamic Memory Allocation 12
Example –malloc()
5/12/2021 2.1 _ Dynamic Memory Allocation 13
• “calloc” or “contiguous allocation” method in C is used to
dynamically allocate the specified number of blocks of
memory of the specified type.
• It initializes each block with a default value ‘0’.
• Allocates the space for elements of an array.
• Initializes the elements to zero and returns a pointer to the
memory.
• Returns NULL if memory is not sufficient.
calloc()
• Syntax
ptr = (cast_type *) calloc (number,byte-size);
• Example
ptr = (int *) calloc(5, sizeof(int));
calloc()
calloc()
5/12/2021 2.1 _ Dynamic Memory Allocation 16
#include <stdio.h> #include <stdlib.h>
int main(){
int* ptr; int n, i;
n = 5;
ptr = (int*)calloc(n , sizeof(int));
if (ptr == NULL) {
printf("Memory not allocated.n");
exit(0);
}
else {
for (i = 0; i < n; ++i)
ptr[i] = i + 1;
printf("The elements of the array are: ");
for (i = 0; i < n; ++i)
printf("%d, ", ptr[i]);
}
return 0;}
Example - calloc()
• malloc() function allocates memory and
leaves the memory uninitialized
• calloc() function allocates memory and
initializes all bits to zero
malloc() vs calloc()
• “realloc” or “re-allocation” method in C is used to
dynamically change the memory allocation of a previously
allocated memory.
• In other words, if the memory previously allocated with the
help of malloc or calloc is insufficient, realloc can be used
to dynamically re-allocate memory.
• re-allocation of memory maintains the already present
value and new blocks will be initialized with default
garbage value.
realloc()
• Syntax
ptr=realloc(ptr, new-size)
• Example
int *ptr;
ptr = (int*)malloc(50 * sizeof(int));
ptr = (int *) realloc(ptr, 60*sizeof(int));
realloc()
realloc()
#include <stdio.h>
int main () {
char *ptr;
ptr = (char *) malloc(10);
strcpy(ptr, "Programming");
printf(" %s, Address = %un", ptr, ptr);
ptr = (char *) realloc(ptr, 20); //ptr is reallocated with new size
strcat(ptr, " In 'C'");
printf(" %s, Address = %un", ptr, ptr);
free(ptr);
return 0;
}
Example
• “free” method in C is used to dynamically de-
allocate the memory.
• Frees or empties the previously allocated memory
space.
• It helps to reduce wastage of memory by freeing it.
• Syntax
free(ptr);
free()
free()
5/12/2021 2.1 _ Dynamic Memory Allocation 24
#include <stdio.h> #include <stdlib.h>
int main(){
int* ptr; int n, i;
n = 5;
ptr = (int*)calloc(n , sizeof(int));
if (ptr == NULL) {
printf("Memory not allocated.n");
exit(0);
}
else {
for (i = 0; i < n; ++i)
ptr[i] = i + 1;
printf("The elements of the array are: ");
for (i = 0; i < n; ++i)
printf("%d, ", ptr[i]);
}
free(ptr);
return 0;}
Example - free()
Thank you
5/12/2021 2.1 _ Dynamic Memory Allocation 26
UNIT II : DMA, Pointers and Functions,
Pointers and Structures
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Perundurai, Erode, Tamilnadu, India
Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018.
20CST21 – Programming and Linear Data Structures
Unit I : Contents
1. Dynamic Memory Allocation
2. Function pointers
3. Calling a function using a function pointer
4. Structures – Introduction
5. Structures in Functions
6. Pointers to structures
7. Accessing structure members
8. Using pointer as a function argument
9. Array of structures
10. Self referential structures.
5/12/2021 28
2.2 _ Function Pointer
Interesting facts about Function Pointers
• Unlike normal pointers, a function pointer points to code,
not data. Typically a function pointer stores the start of
executable code.
• Unlike normal pointers, we do not allocate de-allocate
memory using function pointers.
• A function’s name can also be used to get functions’
address.
• Like normal pointers, we can have an array of function
pointers.
• Function pointer can be used in place of switch case.
• Like normal data pointers, a function pointer can be passed
as an argument and can also be returned from a function.
5/12/2021 2.2 _ Function Pointer 29
Function Pointer
• Function pointer is a pointer variable that points to a function or
stores the address of a function.
• Generally in programming languages, the functions are called using
their name.
• Instead of calling a function using function name, function pointer
calls the function by passing the address of the function.
• Every function code along with its variables is stored in a memory.
Hence, every function has an address.
• Function pointer is also called as subroutine pointer or procedure
pointer.
• Like other pointer variables, function pointer variables can also be
declared, assigned values and used to access the function they
point to.
• The steps for invoking function pointers are
– Declaration of a function pointer
– Initializing a function pointer
– Calling a function using function pointer
5/12/2021 2.2 _ Function Pointer 30
Declaration of a function pointer
• Function pointer has to be declared like the prototype
of the function except that the name of the function
is enclosed between parenthesis () and an asterisk * is
inserted before the name.
• Rules for declaring function pointer is given as follows:
– Return type of the function must match with the datatype
of the function pointer variable.
– Function pointer variable name must be specified within
parenthesis () and it needs to be preceded by asterisk
symbol *.
– The number of arguments and datatype of the argument
in the function pointer variable declaration must be
exactly same as the number and datatype of the
argument in the function.
5/12/2021 2.2 _ Function Pointer 31
Declaration of a function pointer
• The syntax for declaring a function pointer can be
given as:
• Example:
• The above function pointer
– returns a float value and
– accepts two arguments one of integer and other of float
type.
5/12/2021 2.2 _ Function Pointer 32
Declaration of a function pointer
• Suppose, if the function pointer variable is not
declared within parenthesis, then because of
precedence, the declaration of function returns
pointer to a pointer variable.
• In the following declaration, test is not a function
pointer.
• test is a function which returns floating point
address.
5/12/2021 2.2 _ Function Pointer 33
int add(int,int);
Guess the Differences ???
int *add(int,int);
int (*add)(int,int);
5/12/2021 34
2.2 _ Function Pointer
Initializing a function pointer
• After declaration, the function pointer must be
initialized by assigning the address of a function which
has the same signature.
• The syntax for initializing a function pointer is
• Similar to an array, the function name holds the
starting address of the function.
• Hence, the address operator (&) in front of
function_name is optional.
• So the function pointer can also be initialized by
assigning function name without address operator.
5/12/2021 2.2 _ Function Pointer 35
Initializing a function pointer with NULL
• The function pointer can also be declared and
initialize to NULL as given below:
• Example :
5/12/2021 2.2 _ Function Pointer 36
Initializing a function pointer - Example
• Example:
• The function pointer variable can also be
initialized while declaring the function pointer
variable itself.
5/12/2021 2.2 _ Function Pointer 37
Calling a function using Function Pointer
• After initializing the function pointer, the function
can be called in two different ways.
– 1.
– 2.
• The function pointer is also used to call different
functions with same signature at run time.
5/12/2021 2.2 _ Function Pointer 38
Example 1 - Find the sum of two numbers
using function pointer
5/12/2021 2.2 _ Function Pointer 39
5/12/2021 2.2 _ Function Pointer 40
5/12/2021 2.2 _ Function Pointer 41
Example 2 - Perform arithmetic operation
using function pointer
5/12/2021 2.2 _ Function Pointer 42
5/12/2021 2.2 _ Function Pointer 43
5/12/2021 2.2 _ Function Pointer 44
Example 3 - Find the maximum of two numbers
using function pointer
5/12/2021 2.2 _ Function Pointer 45
5/12/2021 2.2 _ Function Pointer 46
Passing a Function
to
another Function
5/12/2021 47
2.2 _ Function Pointer
#include <stdio.h>
int add(int a, int b)
{
return a+b;
}
int sub(int a, int b)
{
return a-b;
}
int arith(int f(int,int))
{
int x=5, y=4,s;
s=(*f)(x,y);
return s;
}
int main()
{
printf("n Add: %d",arith(add));
printf("n Sub: %d",arith(sub));
return 0;
}
5/12/2021 48
2.2 _ Function Pointer
#include <stdio.h>
int even(int a)
{
if(a%2==0)
return a;
else
return 0;
}
int odd(int a)
{
if(a%2!=0)
return a;
else
return 0;
}
int sum(int f(int), int m, int n)
{
int s = 0;
for(int i=m; i<=n;++i)
s+=f(i); or s+=(*f)(i);
return s;
}
int main()
{
printf("n Sum of Even numbers: %d",sum(even,5,10));
printf("n Sum of Odd numbers: %d",sum(odd,5,10));
return 0;
}
5/12/2021 49
2.2 _ Function Pointer
Return a Function Pointer
5/12/2021 50
2.2 _ Function Pointer
#include <stdio.h>
int add(int x,int y)
{
return x + y;
}
int sub(int x,int y)
{
return x - y;
}
int (*getOperator(const char
oper))(int, int)
{
if(oper == '+') return &add;
if(oper == '-') return &sub;
}
int main()
{
int x = 20,y = 10,z = 0;
int (*func)(int, int);
func = getOperator('+');
z = func(x,y);
printf("Add : %dn",z);
func = getOperator('-');
z = func(x,y);
printf("Sub : %dn",z);
return 0;
}
5/12/2021 51
2.2 _ Function Pointer
#include <stdio.h>
#include <stdlib.h>
typedef int(*pfOperator)(int, int);
int add(int x,int y)
{
return x + y;
}
int sub(int x,int y)
{
return x - y;
}
pfOperator getOperator(const
char oper)
{
if(oper == '+') return &add;
if(oper == '-') return &sub;
}
int main()
{
int x = 20,y = 10,z = 0;
pfOperator func = NULL;
func = getOperator('+');
z = func(x,y);
printf("Add : %dn",z);
func = getOperator('-');
z = func(x,y);
printf("Sub : %dn",z);
return 0;
}
5/12/2021 52
2.2 _ Function Pointer
Arrays of Function Pointers
5/12/2021 53
2.2 _ Function Pointer
Arrays of Function Pointer
• Generally, array is a collection of similar data items
that can be stored under a common name.
• Similarly, an array of function pointers is a collection
of function pointers.
• In array of function pointer, addresses of different
functions with same signature are stored under a
single name.
• A function pointer chooses the appropriate function at
runtime which are called using their index value.
• In general, arrays of function pointers are useful where
there is the potential for a range of inputs to a
program, that subsequently alters program flow.
• There are ways of how to define and use an array of
function pointers in C.
5/12/2021 2.2 _ Function Pointer 54
Arrays of Function Pointer - Declaration
• Array of function pointer can be declared in
the following two ways:
5/12/2021 2.2 _ Function Pointer 55
Arrays of Function Pointer - Initialization
• After declaration, the array of function pointer
can be assigned/initialized with function
address using one of two forms.
5/12/2021 2.2 _ Function Pointer 56
Arrays of Function Pointer – Initialization NULL
• During the declaration of array of function
pointer, each element in the array of function
pointer can be initialized as NULL by the
following statements:
5/12/2021 2.2 _ Function Pointer 57
Arrays of Function Pointer – Calling a function
• After assigning the address of a function to an
array of function pointer, the function can be
called as
5/12/2021 2.2 _ Function Pointer 58
#include <stdio.h>
int(*fpointer[2])(int, int);
int add(int a, int b){return(a + b);}
int sub(int a, int b) {return(a - b);}
int main(){
fpointer[0] = &add;
printf("%d n", (*fpointer[0])(4, 5));
fpointer[1] = sub;
printf(“%d n”, fpointer[1](6, 2));
return 0;}
5/12/2021 59
2.2 _ Function Pointer
Thank you
5/12/2021 2.2 _ Function Pointer 60
UNIT II : DMA, Pointers and Functions,
Pointers and Structures
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Perundurai, Erode, Tamilnadu, India
Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018.
20CST21 – Programming and Linear Data Structures
Unit I : Contents
1. Dynamic Memory Allocation
2. Function pointers
3. Calling a function using a function pointer
4. Structures – Introduction
5. Structures in Functions
6. Pointers to structures
7. Accessing structure members
8. Using pointer as a function argument
9. Array of structures
10. Self referential structures.
5/12/2021 62
2.3 _ Pointers and Structures
Structure Introduction
• An array is a collection of similar or
homogeneous data types which could be
stored under a single name.
• But, structure is defined as a collection of
dissimilar or heterogeneous data types that
can be stored under a common name.
• A structure is a user defined data type.
(Others are like Union, Typedef, Enum)
5/12/2021 2.3 _ Pointers and Structures 63
Definition of a structure
• The rules for defining a structure are given below:
– Structure is defined with a struct keyword.
– Each member of the structure definition is similar to a
normal variable definition such as
• int i, float f or any other valid variable definition.
– At the end of the structure definition, the final
semicolon must be placed.
– One or more structural variable can be created but it’s
optional.
– The structure is defined either outside the main
function or inside the main function. Mostly, the
structure is defined outside the main function.
5/12/2021 2.3 _ Pointers and Structures 64
Definition of a structure
5/12/2021 2.3 _ Pointers and Structures 65
Declaration of structure variable
• Memory is allocated only when structure variable is
declared and not during the definition.
• The structure variable can be created using the following
syntax
• The structure variable can also be declared while defining
the structure as given below.
5/12/2021 2.3 _ Pointers and Structures 66
Declaration of structure variable - Example
5/12/2021 2.3 _ Pointers and Structures 67
Initialization of structure variable
• A structure variable can be initialized during
its declaration as follows:
5/12/2021 2.3 _ Pointers and Structures 68
Accessing of structure member
• There are two ways for accessing the
members of a structure. They are,
– Dot operator(.)
– Structure pointer(->)
5/12/2021 2.3 _ Pointers and Structures 69
Dot operator (.)
• The dot operator (.) is used to access the
members of a structure and the syntax is
given below:
• For example, to access the rollno of variable
s1 of student structure, we can use s1.rollno
5/12/2021 2.3 _ Pointers and Structures 70
Example 1
5/12/2021 2.3 _ Pointers and Structures 71
5/12/2021 2.3 _ Pointers and Structures 72
5/12/2021 2.3 _ Pointers and Structures 73
Structure Pointer (->)
• Structure pointer is another method for
accessing the structure member.
• The arrow operator -> is used to access the
member of the structure variable through
pointers.
5/12/2021 2.3 _ Pointers and Structures 74
Example 2
5/12/2021 2.3 _ Pointers and Structures 75
5/12/2021 2.3 _ Pointers and Structures 76
Typedef and its use in structure
declaration
• Typedef is a keyword that is used to give a
new symbolic name (alias or alternate name)
for the existing datatype.
• It is often used to simplify the syntax for
declaring complex data types.
• We can either use existing data type or
new_name for creating variables .
5/12/2021 2.3 _ Pointers and Structures 77
5/12/2021 2.3 _ Pointers and Structures 78
• Structure variable of type student can be created using the newly assigned name temp as
structure name as alias name
• We can also use structure name as alias name
such as,
• Here, we can use the name student for creating
structure variable without using the keyword
struct such as,
5/12/2021 2.3 _ Pointers and Structures 79
Example 3
5/12/2021 2.3 _ Pointers and Structures 80
5/12/2021 2.3 _ Pointers and Structures 81
Example 4 - The another way of defining the structure variable
5/12/2021 2.3 _ Pointers and Structures 82
5/12/2021 2.3 _ Pointers and Structures 83
Nesting of Structure
• Nesting of structure means that defining a
structure as one of the member of another
structure.
• The use of such nested structures facilitates
representation and processing of complex
data.
5/12/2021 2.3 _ Pointers and Structures 84
Nested Structure - Syntax
5/12/2021 2.3 _ Pointers and Structures 85
• First member (in_member1) of the inner structure can be accessed as
Example 5
5/12/2021 2.3 _ Pointers and Structures 86
5/12/2021 2.3 _ Pointers and Structures 87
What is the size of this structure?
5/12/2021 2.3 _ Pointers and Structures 88
Memory Layout of Members of music_cd
• Note that sizeof computes the total memory
occupied by a structure.
• This is not necessarily the sum of the sizes of the
members.
• Thus, on this machine having a 4-byte word.
– title occupies 28 bytes (7 words) even though it uses
27 of them.
– qty and price individually occupy an entire word (4
bytes each), but qty uses two of these bytes.
– disk1 thus needs 33 bytes (27 + 2 + 4) but it actually
occupies 36 bytes.
5/12/2021 2.3 _ Pointers and Structures 89
Memory Layout of Members of music_cd
• Alignment issues related to structures lead to
the creation of slack bytes or holes in the
allocated memory segment.
5/12/2021 2.3 _ Pointers and Structures 90
Size ???
5/12/2021 2.3 _ Pointers and Structures 91
Thank you
5/12/2021 2.3 _ Pointers and Structures 92
UNIT II : DMA, Pointers and Functions,
Pointers and Structures
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Perundurai, Erode, Tamilnadu, India
Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018.
20CST21 – Programming and Linear Data Structures
Unit I : Contents
1. Dynamic Memory Allocation
2. Function pointers
3. Calling a function using a function pointer
4. Structures – Introduction
5. Structures in Functions
6. Pointers to structures
7. Accessing structure members
8. Using pointer as a function argument
9. Array of structures
10. Self referential structures.
5/12/2021 94
2.4 _ Structure in Functions
Structures in Functions - Contents
1. Passing structure variables as arguments to a
function.
1. We can pass individual members of a structure or
2. we can pass entire structure as a whole to a function.
3. Also more than one structure variable can be passes to
a function.
2. Return structure from a function
3. Declaration of Structure Variable as Global Variable
4. Passing array of structures to function
1. Formal Parameter as an array
2. Formal Parameter as a pointer
5/12/2021 2.4 _ Structure in Functions 95
1. Passing structure variables as arguments
• Like a normal variable, the structure variable
may be passed using
– pass-by-value or
– pass-by-address
5/12/2021 2.4 _ Structure in Functions 96
Using pass-by-value
• The structure can be passed to function as an
argument.
• Here, the entire structure with all its members are
passed as an argument to the function.
• It is passed to a function by pass-by-value method.
• Any changes made to the structure variable within
the function will not be reflected in the calling
function.
• If the changes need to be reflected, the updated
structure has to be returned to the calling function.
5/12/2021 2.4 _ Structure in Functions 97
Example – Pass-by-value
5/12/2021 2.4 _ Structure in Functions 98
5/12/2021 2.4 _ Structure in Functions 99
Using Pass-by-address
• We can also use pass-by-address method for
passing the structure to function.
• Here, address of structure is passed to function.
• In this case, whatever the changes made in
formal argument in called function is reflected in
actual argument in calling function.
• In the function, structure should be received by
structure pointer.
• During pass by reference, the memory addresses
of structure variables are passed to the function.
5/12/2021 2.4 _ Structure in Functions 100
Example – Pass-by-address
5/12/2021 2.4 _ Structure in Functions 101
5/12/2021 2.4 _ Structure in Functions 102
5/12/2021 2.4 _ Structure in Functions 103
2. Return structure from a function
• Declare a function with data type as
– struct <structure name> <function name()>;
• To return a structure from a function use the
return keyword as
– return <structure_variable_name>;
5/12/2021 2.4 _ Structure in Functions 104
Example – Return structure from function
5/12/2021 2.4 _ Structure in Functions 105
5/12/2021 2.4 _ Structure in Functions 106
5/12/2021 2.4 _ Structure in Functions 107
3. Declaration of Structure Variable as Global Variable
• Structure variables also can be declared as
global variables which is similar to declaring
other variables.
• If the variable is declared as global, it can be
accessed by all the functions in the program
without passing it as an argument to
function.
5/12/2021 2.4 _ Structure in Functions 108
Example
5/12/2021 2.4 _ Structure in Functions 109
5/12/2021 2.4 _ Structure in Functions 110
4. Passing array of structures to function
• We can also pass entire array of structures to a
function as an argument.
• To pass an entire array to a function, only the
name of the array is passed as an argument.
• When address is passed as an argument, the
function definition should have an array or a
pointer as a parameter to receive the passed
address.
• When an array is passed to a function, the
changes made by the function affect the original
array.
5/12/2021 2.4 _ Structure in Functions 111
Passing array of structures to function
• We can receive an array of structure in a
function using one of the following two
methods :
5/12/2021 2.4 _ Structure in Functions 112
Example – formal parameter as an array
5/12/2021 2.4 _ Structure in Functions 113
5/12/2021 2.4 _ Structure in Functions 114
5/12/2021 2.4 _ Structure in Functions 115
5/12/2021 2.4 _ Structure in Functions 116
Example – formal parameter as a pointer
5/12/2021 2.4 _ Structure in Functions 117
5/12/2021 2.4 _ Structure in Functions 118
5/12/2021 2.4 _ Structure in Functions 119
5/12/2021 2.4 _ Structure in Functions 120
Thank you
5/12/2021 2.4 _ Structure in Functions 121
UNIT II : DMA, Pointers and Functions,
Pointers and Structures
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Perundurai, Erode, Tamilnadu, India
Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018.
20CST21 – Programming and Linear Data Structures
Unit I : Contents
1. Dynamic Memory Allocation
2. Function pointers
3. Calling a function using a function pointer
4. Structures – Introduction
5. Structures in Functions
6. Pointers to structures
7. Accessing structure members
8. Using pointer as a function argument
9. Array of structures
10. Self referential structures.
5/12/2021 123
2.6 _ Pointers to Structures
Pointers to structures
• A pointer to a structure must be defined
before it is pointed to a structure variable.
struct rectangle
{
short length;
short width;
} rect1 = {10, 20};
struct rectangle *p; //Creates pointer p
p = &rect1; //p points to rect1
5/12/2021 2.6 _ Pointers to Structures 124
Accessing structure members
• The structure members can be accessed in three ways.
• Two of them use a pointer with standard and special
notation.
– rect1.length //The standard access mechanism that doesn’t use a
pointer.
– p->length //Uses a special operator, ->, that works only with
structures. It uses a pointer.
– (*p).length //Pointer dereferenced with * and then connected to the
member. It uses a pointer.
• Example:
5/12/2021 2.6 _ Pointers to Structures 125
Example Program
#include <stdio.h>
#include <string.h>
int main(void)
{
struct employee
{
short id;
char name[30];
int pay;
} emp = {1024, “Steve Wozniak”, 10000}, *p;
p = &emp;
printf(“Emp-id: %hd, Name: %s, Pay: %dn”, emp.id, (*p).name, p->pay);
(*p).id = 4201; /* Updates id */
strcpy(p->name, “Steve Jobs”); /* Updates name */
p->pay = 20000; /* Updates pay */
printf(“Emp-id: %hd, Name: %s, Pay: %dn”, p->id, p->name, p->pay);
return 0;
}
5/12/2021 2.6 _ Pointers to Structures 126
Using a Pointer as a Function Argument
• A structure variable can be passed as function arguments.
• This will behave as pass-by-value.
• This mechanism is safe and it protects the original structure
from modification by the function.
• However, large structures can consume a lot of memory, so we
may need to pass a pointer to a structure instead of the entire
structure.
• Updating a member’s value using a pointer represents a
memory-efficient technique because the function copies not
the structure (36 bytes) but its pointer (4 bytes).
5/12/2021 2.6 _ Pointers to Structures 127
Example Program
/* update_pay.c: Uses a pointer to a structure as a function argument to update the
structure. */
#include <stdio.h>
struct employee
{
short id;
char name[30];
int pay;
} emp = {1024, “Steve Wozniak”, 10000};
void update_pay(struct employee *f_emp, int f_pay);
int main(void)
{
printf(“Old pay = %dn”, emp.pay);
update_pay(&emp, 20000);
printf(“New pay = %dn”, emp.pay);
return 0;
}
5/12/2021 2.6 _ Pointers to Structures 128
Example Program
void update_pay(struct employee *f_emp, int f_pay)
{
f_emp->pay = f_pay; /* Updates member pay of emp */
}
OUTPUT:
Old pay = 10000
New pay = 20000
5/12/2021 2.6 _ Pointers to Structures 129
Thank you
5/12/2021 2.6 _ Pointers to Structures 130
UNIT II : DMA, Pointers and Functions,
Pointers and Structures
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Perundurai, Erode, Tamilnadu, India
Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018.
20CST21 – Programming and Linear Data Structures
Unit I : Contents
1. Dynamic Memory Allocation
2. Function pointers
3. Calling a function using a function pointer
4. Structures – Introduction
5. Structures in Functions
6. Pointers to structures
7. Accessing structure members
8. Using pointer as a function argument
9. Array of structures
10. Self referential structures
5/12/2021 132
2.6 _ Array of Structure and Self Referential
Structures
Arrays Of Structures
• An array of structures is a collection of
structures and therefore, each element of an
array is of same structure type.
• If the user needs to store more than one
record of same structure type, we have to
create an array of structure.
5/12/2021
2.6 _ Array of Structure and Self Referential
Structures
133
Arrays Of Structures
• Suppose, to handle two students data we can use the
two structure variables, stud1 and stud2.
• This technique won’t work with 500 students.
• C supports an array of structures, whose definition
may or may not be combined with the declaration of
the structure.
• The following statement defines an array of type struct
student that can hold 50 sets (or records) of student
data.
5/12/2021
2.6 _ Array of Structure and Self Referential
Structures
134
Syntax for declaring structure array and
accessing member
5/12/2021
2.6 _ Array of Structure and Self Referential
Structures
135
Arrays Of Structures
• Alternatively, you can separate the declaration and
definition.
• You can also use typedef to replace struct student with
STUDENT.
5/12/2021
2.6 _ Array of Structure and Self Referential
Structures
136
Array of Structures
• This array can be partially or fully initialized by
enclosing the initializers for each array element in a set
of curly braces.
• Each set is separated from its adjacent one by a
comma, while the entire set of initializers are enclosed
by outermost braces:
5/12/2021
2.6 _ Array of Structure and Self Referential
Structures
137
Array of Structures
• Each member of each element of this array is accessed
by using a dot to connect the member to its array
element.
• You can use scanf to input values to each member
using pointers to these variables (like &stud[i].marks).
• A simple for loop using the array index as the key
variable prints the entire list.
5/12/2021
2.6 _ Array of Structure and Self Referential
Structures
138
Example
5/12/2021
2.6 _ Array of Structure and Self Referential
Structures
139
5/12/2021
2.6 _ Array of Structure and Self Referential
Structures
140
Self Referential Structures
• Self Referential structures are structures that
have one or more pointers which point to the
same type of structure, as their member.
• In other words, structures pointing to the
same type of structures are self-referential in
nature.
5/12/2021
2.6 _ Array of Structure and Self Referential
Structures
141
Self Referential Structures
5/12/2021
2.6 _ Array of Structure and Self Referential
Structures
142
Example
• In the above example ‘link’ is a pointer to a structure of
type ‘node’.
• Hence, the structure ‘node’ is a self-referential structure
with ‘link’ as the referencing pointer.
• An important point to consider is that the pointer should
be initialized properly before accessing, as by default it
contains garbage value.
5/12/2021
2.6 _ Array of Structure and Self Referential
Structures
143
Types of Self Referential Structures
• Self Referential Structure with Single Link
• Self Referential Structure with Multiple Links
5/12/2021
2.6 _ Array of Structure and Self Referential
Structures
144
Self Referential Structure with Single Link
• These structures can have only one self-
pointer as their member.
• The following example will show us how to
connect the objects of a self-referential
structure with the single link and access the
corresponding data members.
• The connection formed is shown in the
following figure.
5/12/2021
2.6 _ Array of Structure and Self Referential
Structures
145
Example
5/12/2021
2.6 _ Array of Structure and Self Referential
Structures
146
5/12/2021
2.6 _ Array of Structure and Self Referential
Structures
147
10 20 X
30 40 X
Self Referential Structure with Multiple Link
• Self referential structures with multiple links can
have more than one self-pointers.
• Many complicated data structures can be easily
constructed using these structures.
• Such structures can easily connect to more than
one nodes at a time.
• The following example shows one such structure
with more than one links.
• The connections made in the above example can
be understood using the following figure.
5/12/2021
2.6 _ Array of Structure and Self Referential
Structures
148
Example
5/12/2021
2.6 _ Array of Structure and Self Referential
Structures
149
X 10 X
X 20 X
X 30 X
5/12/2021
2.6 _ Array of Structure and Self Referential
Structures
150
Applications of Self Referential Structures
• Self referential structures are very useful in
creation of other complex data structures like:
– Linked Lists
– Stacks
– Queues
– Trees
– Graphs etc
5/12/2021
2.6 _ Array of Structure and Self Referential
Structures
151
Thank you
5/12/2021
2.6 _ Array of Structure and Self Referential
Structures
152

More Related Content

PPTX
Data Structures - Lecture 7 [Linked List]
PPTX
Hashing in datastructure
PPTX
Data Structures - Lecture 9 [Stack & Queue using Linked List]
PPTX
Array Of Pointers
PPT
PPTX
Linked List
PPT
Linked list
PDF
linked lists in data structures
Data Structures - Lecture 7 [Linked List]
Hashing in datastructure
Data Structures - Lecture 9 [Stack & Queue using Linked List]
Array Of Pointers
Linked List
Linked list
linked lists in data structures

What's hot (20)

PPTX
Sparse matrix and its representation data structure
PDF
Arrays in python
PPTX
Searching and sorting
PDF
Data Structures
PPT
BINARY TREE REPRESENTATION.ppt
PPTX
Unary operator overloading
PPTX
queue & its applications
PPT
Pointers in c
PPT
Memory allocation in c
PPTX
Recursion in Data Structure
PPTX
Dynamic memory allocation in c++
PPTX
The Stack And Recursion
PPTX
parameter passing in c#
PPT
Binary tree
PPTX
Binary Tree in Data Structure
PPTX
2- Dimensional Arrays
PPTX
Linked list
PDF
POINTERS IN C MRS.SOWMYA JYOTHI.pdf
PPTX
Ppt on Linked list,stack,queue
PPT
Circular linked list
Sparse matrix and its representation data structure
Arrays in python
Searching and sorting
Data Structures
BINARY TREE REPRESENTATION.ppt
Unary operator overloading
queue & its applications
Pointers in c
Memory allocation in c
Recursion in Data Structure
Dynamic memory allocation in c++
The Stack And Recursion
parameter passing in c#
Binary tree
Binary Tree in Data Structure
2- Dimensional Arrays
Linked list
POINTERS IN C MRS.SOWMYA JYOTHI.pdf
Ppt on Linked list,stack,queue
Circular linked list
Ad

Similar to Dynamic Memory Allocation, Pointers and Functions, Pointers and Structures (20)

PPTX
BBACA-SEM-III-Datastructure-PPT(0) for third semestetr
PPTX
pointers in c programming - example programs
PPT
Lecture 18 - Pointers
PPTX
pointer_in_c_programming_structure and uses.pptx
PPTX
Programming in C sesion 2
PPTX
Dynamic Memory Allocation in C
PPT
Advanced pointers
PPTX
POINTERS in C language:- Mastering-Pointers-in-C
PPTX
Advance topics of C language
PDF
Dynamic memory allocation
PPTX
Unit-9zxknaksldmoasdoiasmdmiojoisa(DMA).pptx
PDF
C Recursion, Pointers, Dynamic memory management
PDF
C Programming - Refresher - Part III
PPTX
Pointers and Dynamic Memory Allocation
PDF
0-Slot11-12-Pointers.pdf
PPT
CLanguage_ClassPPT_3110003_unit 9Material.ppt
PDF
C++_notes.pdf
PPT
Chapter09-10 Pointers and operations .PPT
PPT
Chapter09-10.PPT
BBACA-SEM-III-Datastructure-PPT(0) for third semestetr
pointers in c programming - example programs
Lecture 18 - Pointers
pointer_in_c_programming_structure and uses.pptx
Programming in C sesion 2
Dynamic Memory Allocation in C
Advanced pointers
POINTERS in C language:- Mastering-Pointers-in-C
Advance topics of C language
Dynamic memory allocation
Unit-9zxknaksldmoasdoiasmdmiojoisa(DMA).pptx
C Recursion, Pointers, Dynamic memory management
C Programming - Refresher - Part III
Pointers and Dynamic Memory Allocation
0-Slot11-12-Pointers.pdf
CLanguage_ClassPPT_3110003_unit 9Material.ppt
C++_notes.pdf
Chapter09-10 Pointers and operations .PPT
Chapter09-10.PPT
Ad

More from Selvaraj Seerangan (20)

PDF
Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...
PDF
Unit 5 _ Fog Computing .pdf
PDF
CAT III Answer Key.pdf
PPTX
END SEM _ Design Thinking _ 16 Templates.pptx
PPTX
Design Thinking _ Complete Templates.pptx
PPTX
CAT 3 _ List of Templates.pptx
PPTX
[PPT] _ Unit 5 _ Evolve.pptx
PPTX
[PPT] _ Unit 4 _ Engage.pptx
PPTX
[PPT] _ Unit 3 _ Experiment.pptx
PPTX
CAT 2 _ List of Templates.pptx
PPTX
Design Thinking - Empathize Phase
PDF
CAT-II Answer Key.pdf
PDF
PSP LAB MANUAL.pdf
PDF
18CSL51 - Network Lab Manual.pdf
PDF
DS LAB MANUAL.pdf
PPTX
CAT 1 _ List of Templates.pptx
PPTX
[PPT] _ UNIT 1 _ COMPLETE.pptx
DOC
CAT-1 Answer Key.doc
PPTX
Unit 3 Complete.pptx
PDF
[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf
Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...
Unit 5 _ Fog Computing .pdf
CAT III Answer Key.pdf
END SEM _ Design Thinking _ 16 Templates.pptx
Design Thinking _ Complete Templates.pptx
CAT 3 _ List of Templates.pptx
[PPT] _ Unit 5 _ Evolve.pptx
[PPT] _ Unit 4 _ Engage.pptx
[PPT] _ Unit 3 _ Experiment.pptx
CAT 2 _ List of Templates.pptx
Design Thinking - Empathize Phase
CAT-II Answer Key.pdf
PSP LAB MANUAL.pdf
18CSL51 - Network Lab Manual.pdf
DS LAB MANUAL.pdf
CAT 1 _ List of Templates.pptx
[PPT] _ UNIT 1 _ COMPLETE.pptx
CAT-1 Answer Key.doc
Unit 3 Complete.pptx
[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf

Recently uploaded (20)

PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PPTX
Sustainable Sites - Green Building Construction
PPTX
Construction Project Organization Group 2.pptx
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PPTX
Internet of Things (IOT) - A guide to understanding
PPTX
CH1 Production IntroductoryConcepts.pptx
PPTX
OOP with Java - Java Introduction (Basics)
PPTX
UNIT 4 Total Quality Management .pptx
PPTX
bas. eng. economics group 4 presentation 1.pptx
PDF
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PPTX
Geodesy 1.pptx...............................................
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
PDF
PPT on Performance Review to get promotions
PDF
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
PPTX
UNIT-1 - COAL BASED THERMAL POWER PLANTS
PPTX
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PPTX
Welding lecture in detail for understanding
CYBER-CRIMES AND SECURITY A guide to understanding
Model Code of Practice - Construction Work - 21102022 .pdf
Sustainable Sites - Green Building Construction
Construction Project Organization Group 2.pptx
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
Internet of Things (IOT) - A guide to understanding
CH1 Production IntroductoryConcepts.pptx
OOP with Java - Java Introduction (Basics)
UNIT 4 Total Quality Management .pptx
bas. eng. economics group 4 presentation 1.pptx
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
Geodesy 1.pptx...............................................
Embodied AI: Ushering in the Next Era of Intelligent Systems
PPT on Performance Review to get promotions
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
UNIT-1 - COAL BASED THERMAL POWER PLANTS
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
Welding lecture in detail for understanding

Dynamic Memory Allocation, Pointers and Functions, Pointers and Structures

  • 1. UNIT II : DMA, Pointers and Functions, Pointers and Structures By Mr.S.Selvaraj Asst. Professor (SRG) / CSE Kongu Engineering College Perundurai, Erode, Tamilnadu, India Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018. 20CST21 – Programming and Linear Data Structures
  • 2. Syllabus – Unit Wise 5/12/2021 2.1 _ Dynamic Memory Allocation 2
  • 3. List of Exercises 5/12/2021 2.1 _ Dynamic Memory Allocation 3
  • 4. Text Book and Reference Book 5/12/2021 2.1 _ Dynamic Memory Allocation 4
  • 5. Unit I : Contents 1. Dynamic Memory Allocation 2. Function pointers 3. Calling a function using a function pointer 4. Structures – Introduction 5. Structures in Functions 6. Pointers to structures 7. Accessing structure members 8. Using pointer as a function argument 9. Array of structures 10. Self referential structures. 5/12/2021 5 2.1 _ Dynamic Memory Allocation
  • 6. Dynamic Memory Allocation • While programming, if we know the amount of memory required prior, then we can allocate memory in advance during compile time itself. • For example, to store a name of any employee whose name may go up to a maximum of 50 characters, we can define it using array as follows: 5/12/2021 2.1 _ Dynamic Memory Allocation 6
  • 7. Dynamic Memory Allocation • But there might be a situation when we have to allocate memory based on the user requirement i.e., amount of memory needed may change over time. • For example, Let us consider a situation where we have no idea about the length of the text like detailed description about a topic. • Here we need to define a pointer to character without defining how much memory is required and later, based on the requirement, we can allocate memory during execution time. • The process of allocating memory during program execution is called dynamic memory allocation. 5/12/2021 2.1 _ Dynamic Memory Allocation 7
  • 8. Difference between static memory allocation and dynamic memory allocation 5/12/2021 2.1 _ Dynamic Memory Allocation 8
  • 9. Dynamic memory allocation functions • The C language offers the following dynamic memory allocation functions in stdlib.h header file. 5/12/2021 2.1 _ Dynamic Memory Allocation 9
  • 10. malloc() function • “malloc” or “memory allocation” • malloc () function is used to allocate space in memory during the execution of the program. • malloc() allocates memory block of given size (in bytes) and returns a pointer to the beginning of the block. • It returns a pointer of type void which can be cast into a pointer of any form. • The malloc() function allocates single block of requested memory. • It does not initialize memory at execution time, so the allocated memory is filled with some garbage value. • It returns NULL if sufficient memory is not allocated. 5/12/2021 2.1 _ Dynamic Memory Allocation 10
  • 11. malloc() function • The syntax of malloc() function is given below: 5/12/2021 2.1 _ Dynamic Memory Allocation 11
  • 12. malloc() function 5/12/2021 2.1 _ Dynamic Memory Allocation 12
  • 13. Example –malloc() 5/12/2021 2.1 _ Dynamic Memory Allocation 13
  • 14. • “calloc” or “contiguous allocation” method in C is used to dynamically allocate the specified number of blocks of memory of the specified type. • It initializes each block with a default value ‘0’. • Allocates the space for elements of an array. • Initializes the elements to zero and returns a pointer to the memory. • Returns NULL if memory is not sufficient. calloc()
  • 15. • Syntax ptr = (cast_type *) calloc (number,byte-size); • Example ptr = (int *) calloc(5, sizeof(int)); calloc()
  • 16. calloc() 5/12/2021 2.1 _ Dynamic Memory Allocation 16
  • 17. #include <stdio.h> #include <stdlib.h> int main(){ int* ptr; int n, i; n = 5; ptr = (int*)calloc(n , sizeof(int)); if (ptr == NULL) { printf("Memory not allocated.n"); exit(0); } else { for (i = 0; i < n; ++i) ptr[i] = i + 1; printf("The elements of the array are: "); for (i = 0; i < n; ++i) printf("%d, ", ptr[i]); } return 0;} Example - calloc()
  • 18. • malloc() function allocates memory and leaves the memory uninitialized • calloc() function allocates memory and initializes all bits to zero malloc() vs calloc()
  • 19. • “realloc” or “re-allocation” method in C is used to dynamically change the memory allocation of a previously allocated memory. • In other words, if the memory previously allocated with the help of malloc or calloc is insufficient, realloc can be used to dynamically re-allocate memory. • re-allocation of memory maintains the already present value and new blocks will be initialized with default garbage value. realloc()
  • 20. • Syntax ptr=realloc(ptr, new-size) • Example int *ptr; ptr = (int*)malloc(50 * sizeof(int)); ptr = (int *) realloc(ptr, 60*sizeof(int)); realloc()
  • 22. #include <stdio.h> int main () { char *ptr; ptr = (char *) malloc(10); strcpy(ptr, "Programming"); printf(" %s, Address = %un", ptr, ptr); ptr = (char *) realloc(ptr, 20); //ptr is reallocated with new size strcat(ptr, " In 'C'"); printf(" %s, Address = %un", ptr, ptr); free(ptr); return 0; } Example
  • 23. • “free” method in C is used to dynamically de- allocate the memory. • Frees or empties the previously allocated memory space. • It helps to reduce wastage of memory by freeing it. • Syntax free(ptr); free()
  • 24. free() 5/12/2021 2.1 _ Dynamic Memory Allocation 24
  • 25. #include <stdio.h> #include <stdlib.h> int main(){ int* ptr; int n, i; n = 5; ptr = (int*)calloc(n , sizeof(int)); if (ptr == NULL) { printf("Memory not allocated.n"); exit(0); } else { for (i = 0; i < n; ++i) ptr[i] = i + 1; printf("The elements of the array are: "); for (i = 0; i < n; ++i) printf("%d, ", ptr[i]); } free(ptr); return 0;} Example - free()
  • 26. Thank you 5/12/2021 2.1 _ Dynamic Memory Allocation 26
  • 27. UNIT II : DMA, Pointers and Functions, Pointers and Structures By Mr.S.Selvaraj Asst. Professor (SRG) / CSE Kongu Engineering College Perundurai, Erode, Tamilnadu, India Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018. 20CST21 – Programming and Linear Data Structures
  • 28. Unit I : Contents 1. Dynamic Memory Allocation 2. Function pointers 3. Calling a function using a function pointer 4. Structures – Introduction 5. Structures in Functions 6. Pointers to structures 7. Accessing structure members 8. Using pointer as a function argument 9. Array of structures 10. Self referential structures. 5/12/2021 28 2.2 _ Function Pointer
  • 29. Interesting facts about Function Pointers • Unlike normal pointers, a function pointer points to code, not data. Typically a function pointer stores the start of executable code. • Unlike normal pointers, we do not allocate de-allocate memory using function pointers. • A function’s name can also be used to get functions’ address. • Like normal pointers, we can have an array of function pointers. • Function pointer can be used in place of switch case. • Like normal data pointers, a function pointer can be passed as an argument and can also be returned from a function. 5/12/2021 2.2 _ Function Pointer 29
  • 30. Function Pointer • Function pointer is a pointer variable that points to a function or stores the address of a function. • Generally in programming languages, the functions are called using their name. • Instead of calling a function using function name, function pointer calls the function by passing the address of the function. • Every function code along with its variables is stored in a memory. Hence, every function has an address. • Function pointer is also called as subroutine pointer or procedure pointer. • Like other pointer variables, function pointer variables can also be declared, assigned values and used to access the function they point to. • The steps for invoking function pointers are – Declaration of a function pointer – Initializing a function pointer – Calling a function using function pointer 5/12/2021 2.2 _ Function Pointer 30
  • 31. Declaration of a function pointer • Function pointer has to be declared like the prototype of the function except that the name of the function is enclosed between parenthesis () and an asterisk * is inserted before the name. • Rules for declaring function pointer is given as follows: – Return type of the function must match with the datatype of the function pointer variable. – Function pointer variable name must be specified within parenthesis () and it needs to be preceded by asterisk symbol *. – The number of arguments and datatype of the argument in the function pointer variable declaration must be exactly same as the number and datatype of the argument in the function. 5/12/2021 2.2 _ Function Pointer 31
  • 32. Declaration of a function pointer • The syntax for declaring a function pointer can be given as: • Example: • The above function pointer – returns a float value and – accepts two arguments one of integer and other of float type. 5/12/2021 2.2 _ Function Pointer 32
  • 33. Declaration of a function pointer • Suppose, if the function pointer variable is not declared within parenthesis, then because of precedence, the declaration of function returns pointer to a pointer variable. • In the following declaration, test is not a function pointer. • test is a function which returns floating point address. 5/12/2021 2.2 _ Function Pointer 33
  • 34. int add(int,int); Guess the Differences ??? int *add(int,int); int (*add)(int,int); 5/12/2021 34 2.2 _ Function Pointer
  • 35. Initializing a function pointer • After declaration, the function pointer must be initialized by assigning the address of a function which has the same signature. • The syntax for initializing a function pointer is • Similar to an array, the function name holds the starting address of the function. • Hence, the address operator (&) in front of function_name is optional. • So the function pointer can also be initialized by assigning function name without address operator. 5/12/2021 2.2 _ Function Pointer 35
  • 36. Initializing a function pointer with NULL • The function pointer can also be declared and initialize to NULL as given below: • Example : 5/12/2021 2.2 _ Function Pointer 36
  • 37. Initializing a function pointer - Example • Example: • The function pointer variable can also be initialized while declaring the function pointer variable itself. 5/12/2021 2.2 _ Function Pointer 37
  • 38. Calling a function using Function Pointer • After initializing the function pointer, the function can be called in two different ways. – 1. – 2. • The function pointer is also used to call different functions with same signature at run time. 5/12/2021 2.2 _ Function Pointer 38
  • 39. Example 1 - Find the sum of two numbers using function pointer 5/12/2021 2.2 _ Function Pointer 39
  • 40. 5/12/2021 2.2 _ Function Pointer 40
  • 41. 5/12/2021 2.2 _ Function Pointer 41
  • 42. Example 2 - Perform arithmetic operation using function pointer 5/12/2021 2.2 _ Function Pointer 42
  • 43. 5/12/2021 2.2 _ Function Pointer 43
  • 44. 5/12/2021 2.2 _ Function Pointer 44
  • 45. Example 3 - Find the maximum of two numbers using function pointer 5/12/2021 2.2 _ Function Pointer 45
  • 46. 5/12/2021 2.2 _ Function Pointer 46
  • 47. Passing a Function to another Function 5/12/2021 47 2.2 _ Function Pointer
  • 48. #include <stdio.h> int add(int a, int b) { return a+b; } int sub(int a, int b) { return a-b; } int arith(int f(int,int)) { int x=5, y=4,s; s=(*f)(x,y); return s; } int main() { printf("n Add: %d",arith(add)); printf("n Sub: %d",arith(sub)); return 0; } 5/12/2021 48 2.2 _ Function Pointer
  • 49. #include <stdio.h> int even(int a) { if(a%2==0) return a; else return 0; } int odd(int a) { if(a%2!=0) return a; else return 0; } int sum(int f(int), int m, int n) { int s = 0; for(int i=m; i<=n;++i) s+=f(i); or s+=(*f)(i); return s; } int main() { printf("n Sum of Even numbers: %d",sum(even,5,10)); printf("n Sum of Odd numbers: %d",sum(odd,5,10)); return 0; } 5/12/2021 49 2.2 _ Function Pointer
  • 50. Return a Function Pointer 5/12/2021 50 2.2 _ Function Pointer
  • 51. #include <stdio.h> int add(int x,int y) { return x + y; } int sub(int x,int y) { return x - y; } int (*getOperator(const char oper))(int, int) { if(oper == '+') return &add; if(oper == '-') return &sub; } int main() { int x = 20,y = 10,z = 0; int (*func)(int, int); func = getOperator('+'); z = func(x,y); printf("Add : %dn",z); func = getOperator('-'); z = func(x,y); printf("Sub : %dn",z); return 0; } 5/12/2021 51 2.2 _ Function Pointer
  • 52. #include <stdio.h> #include <stdlib.h> typedef int(*pfOperator)(int, int); int add(int x,int y) { return x + y; } int sub(int x,int y) { return x - y; } pfOperator getOperator(const char oper) { if(oper == '+') return &add; if(oper == '-') return &sub; } int main() { int x = 20,y = 10,z = 0; pfOperator func = NULL; func = getOperator('+'); z = func(x,y); printf("Add : %dn",z); func = getOperator('-'); z = func(x,y); printf("Sub : %dn",z); return 0; } 5/12/2021 52 2.2 _ Function Pointer
  • 53. Arrays of Function Pointers 5/12/2021 53 2.2 _ Function Pointer
  • 54. Arrays of Function Pointer • Generally, array is a collection of similar data items that can be stored under a common name. • Similarly, an array of function pointers is a collection of function pointers. • In array of function pointer, addresses of different functions with same signature are stored under a single name. • A function pointer chooses the appropriate function at runtime which are called using their index value. • In general, arrays of function pointers are useful where there is the potential for a range of inputs to a program, that subsequently alters program flow. • There are ways of how to define and use an array of function pointers in C. 5/12/2021 2.2 _ Function Pointer 54
  • 55. Arrays of Function Pointer - Declaration • Array of function pointer can be declared in the following two ways: 5/12/2021 2.2 _ Function Pointer 55
  • 56. Arrays of Function Pointer - Initialization • After declaration, the array of function pointer can be assigned/initialized with function address using one of two forms. 5/12/2021 2.2 _ Function Pointer 56
  • 57. Arrays of Function Pointer – Initialization NULL • During the declaration of array of function pointer, each element in the array of function pointer can be initialized as NULL by the following statements: 5/12/2021 2.2 _ Function Pointer 57
  • 58. Arrays of Function Pointer – Calling a function • After assigning the address of a function to an array of function pointer, the function can be called as 5/12/2021 2.2 _ Function Pointer 58
  • 59. #include <stdio.h> int(*fpointer[2])(int, int); int add(int a, int b){return(a + b);} int sub(int a, int b) {return(a - b);} int main(){ fpointer[0] = &add; printf("%d n", (*fpointer[0])(4, 5)); fpointer[1] = sub; printf(“%d n”, fpointer[1](6, 2)); return 0;} 5/12/2021 59 2.2 _ Function Pointer
  • 60. Thank you 5/12/2021 2.2 _ Function Pointer 60
  • 61. UNIT II : DMA, Pointers and Functions, Pointers and Structures By Mr.S.Selvaraj Asst. Professor (SRG) / CSE Kongu Engineering College Perundurai, Erode, Tamilnadu, India Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018. 20CST21 – Programming and Linear Data Structures
  • 62. Unit I : Contents 1. Dynamic Memory Allocation 2. Function pointers 3. Calling a function using a function pointer 4. Structures – Introduction 5. Structures in Functions 6. Pointers to structures 7. Accessing structure members 8. Using pointer as a function argument 9. Array of structures 10. Self referential structures. 5/12/2021 62 2.3 _ Pointers and Structures
  • 63. Structure Introduction • An array is a collection of similar or homogeneous data types which could be stored under a single name. • But, structure is defined as a collection of dissimilar or heterogeneous data types that can be stored under a common name. • A structure is a user defined data type. (Others are like Union, Typedef, Enum) 5/12/2021 2.3 _ Pointers and Structures 63
  • 64. Definition of a structure • The rules for defining a structure are given below: – Structure is defined with a struct keyword. – Each member of the structure definition is similar to a normal variable definition such as • int i, float f or any other valid variable definition. – At the end of the structure definition, the final semicolon must be placed. – One or more structural variable can be created but it’s optional. – The structure is defined either outside the main function or inside the main function. Mostly, the structure is defined outside the main function. 5/12/2021 2.3 _ Pointers and Structures 64
  • 65. Definition of a structure 5/12/2021 2.3 _ Pointers and Structures 65
  • 66. Declaration of structure variable • Memory is allocated only when structure variable is declared and not during the definition. • The structure variable can be created using the following syntax • The structure variable can also be declared while defining the structure as given below. 5/12/2021 2.3 _ Pointers and Structures 66
  • 67. Declaration of structure variable - Example 5/12/2021 2.3 _ Pointers and Structures 67
  • 68. Initialization of structure variable • A structure variable can be initialized during its declaration as follows: 5/12/2021 2.3 _ Pointers and Structures 68
  • 69. Accessing of structure member • There are two ways for accessing the members of a structure. They are, – Dot operator(.) – Structure pointer(->) 5/12/2021 2.3 _ Pointers and Structures 69
  • 70. Dot operator (.) • The dot operator (.) is used to access the members of a structure and the syntax is given below: • For example, to access the rollno of variable s1 of student structure, we can use s1.rollno 5/12/2021 2.3 _ Pointers and Structures 70
  • 71. Example 1 5/12/2021 2.3 _ Pointers and Structures 71
  • 72. 5/12/2021 2.3 _ Pointers and Structures 72
  • 73. 5/12/2021 2.3 _ Pointers and Structures 73
  • 74. Structure Pointer (->) • Structure pointer is another method for accessing the structure member. • The arrow operator -> is used to access the member of the structure variable through pointers. 5/12/2021 2.3 _ Pointers and Structures 74
  • 75. Example 2 5/12/2021 2.3 _ Pointers and Structures 75
  • 76. 5/12/2021 2.3 _ Pointers and Structures 76
  • 77. Typedef and its use in structure declaration • Typedef is a keyword that is used to give a new symbolic name (alias or alternate name) for the existing datatype. • It is often used to simplify the syntax for declaring complex data types. • We can either use existing data type or new_name for creating variables . 5/12/2021 2.3 _ Pointers and Structures 77
  • 78. 5/12/2021 2.3 _ Pointers and Structures 78 • Structure variable of type student can be created using the newly assigned name temp as
  • 79. structure name as alias name • We can also use structure name as alias name such as, • Here, we can use the name student for creating structure variable without using the keyword struct such as, 5/12/2021 2.3 _ Pointers and Structures 79
  • 80. Example 3 5/12/2021 2.3 _ Pointers and Structures 80
  • 81. 5/12/2021 2.3 _ Pointers and Structures 81
  • 82. Example 4 - The another way of defining the structure variable 5/12/2021 2.3 _ Pointers and Structures 82
  • 83. 5/12/2021 2.3 _ Pointers and Structures 83
  • 84. Nesting of Structure • Nesting of structure means that defining a structure as one of the member of another structure. • The use of such nested structures facilitates representation and processing of complex data. 5/12/2021 2.3 _ Pointers and Structures 84
  • 85. Nested Structure - Syntax 5/12/2021 2.3 _ Pointers and Structures 85 • First member (in_member1) of the inner structure can be accessed as
  • 86. Example 5 5/12/2021 2.3 _ Pointers and Structures 86
  • 87. 5/12/2021 2.3 _ Pointers and Structures 87
  • 88. What is the size of this structure? 5/12/2021 2.3 _ Pointers and Structures 88
  • 89. Memory Layout of Members of music_cd • Note that sizeof computes the total memory occupied by a structure. • This is not necessarily the sum of the sizes of the members. • Thus, on this machine having a 4-byte word. – title occupies 28 bytes (7 words) even though it uses 27 of them. – qty and price individually occupy an entire word (4 bytes each), but qty uses two of these bytes. – disk1 thus needs 33 bytes (27 + 2 + 4) but it actually occupies 36 bytes. 5/12/2021 2.3 _ Pointers and Structures 89
  • 90. Memory Layout of Members of music_cd • Alignment issues related to structures lead to the creation of slack bytes or holes in the allocated memory segment. 5/12/2021 2.3 _ Pointers and Structures 90
  • 91. Size ??? 5/12/2021 2.3 _ Pointers and Structures 91
  • 92. Thank you 5/12/2021 2.3 _ Pointers and Structures 92
  • 93. UNIT II : DMA, Pointers and Functions, Pointers and Structures By Mr.S.Selvaraj Asst. Professor (SRG) / CSE Kongu Engineering College Perundurai, Erode, Tamilnadu, India Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018. 20CST21 – Programming and Linear Data Structures
  • 94. Unit I : Contents 1. Dynamic Memory Allocation 2. Function pointers 3. Calling a function using a function pointer 4. Structures – Introduction 5. Structures in Functions 6. Pointers to structures 7. Accessing structure members 8. Using pointer as a function argument 9. Array of structures 10. Self referential structures. 5/12/2021 94 2.4 _ Structure in Functions
  • 95. Structures in Functions - Contents 1. Passing structure variables as arguments to a function. 1. We can pass individual members of a structure or 2. we can pass entire structure as a whole to a function. 3. Also more than one structure variable can be passes to a function. 2. Return structure from a function 3. Declaration of Structure Variable as Global Variable 4. Passing array of structures to function 1. Formal Parameter as an array 2. Formal Parameter as a pointer 5/12/2021 2.4 _ Structure in Functions 95
  • 96. 1. Passing structure variables as arguments • Like a normal variable, the structure variable may be passed using – pass-by-value or – pass-by-address 5/12/2021 2.4 _ Structure in Functions 96
  • 97. Using pass-by-value • The structure can be passed to function as an argument. • Here, the entire structure with all its members are passed as an argument to the function. • It is passed to a function by pass-by-value method. • Any changes made to the structure variable within the function will not be reflected in the calling function. • If the changes need to be reflected, the updated structure has to be returned to the calling function. 5/12/2021 2.4 _ Structure in Functions 97
  • 98. Example – Pass-by-value 5/12/2021 2.4 _ Structure in Functions 98
  • 99. 5/12/2021 2.4 _ Structure in Functions 99
  • 100. Using Pass-by-address • We can also use pass-by-address method for passing the structure to function. • Here, address of structure is passed to function. • In this case, whatever the changes made in formal argument in called function is reflected in actual argument in calling function. • In the function, structure should be received by structure pointer. • During pass by reference, the memory addresses of structure variables are passed to the function. 5/12/2021 2.4 _ Structure in Functions 100
  • 101. Example – Pass-by-address 5/12/2021 2.4 _ Structure in Functions 101
  • 102. 5/12/2021 2.4 _ Structure in Functions 102
  • 103. 5/12/2021 2.4 _ Structure in Functions 103
  • 104. 2. Return structure from a function • Declare a function with data type as – struct <structure name> <function name()>; • To return a structure from a function use the return keyword as – return <structure_variable_name>; 5/12/2021 2.4 _ Structure in Functions 104
  • 105. Example – Return structure from function 5/12/2021 2.4 _ Structure in Functions 105
  • 106. 5/12/2021 2.4 _ Structure in Functions 106
  • 107. 5/12/2021 2.4 _ Structure in Functions 107
  • 108. 3. Declaration of Structure Variable as Global Variable • Structure variables also can be declared as global variables which is similar to declaring other variables. • If the variable is declared as global, it can be accessed by all the functions in the program without passing it as an argument to function. 5/12/2021 2.4 _ Structure in Functions 108
  • 109. Example 5/12/2021 2.4 _ Structure in Functions 109
  • 110. 5/12/2021 2.4 _ Structure in Functions 110
  • 111. 4. Passing array of structures to function • We can also pass entire array of structures to a function as an argument. • To pass an entire array to a function, only the name of the array is passed as an argument. • When address is passed as an argument, the function definition should have an array or a pointer as a parameter to receive the passed address. • When an array is passed to a function, the changes made by the function affect the original array. 5/12/2021 2.4 _ Structure in Functions 111
  • 112. Passing array of structures to function • We can receive an array of structure in a function using one of the following two methods : 5/12/2021 2.4 _ Structure in Functions 112
  • 113. Example – formal parameter as an array 5/12/2021 2.4 _ Structure in Functions 113
  • 114. 5/12/2021 2.4 _ Structure in Functions 114
  • 115. 5/12/2021 2.4 _ Structure in Functions 115
  • 116. 5/12/2021 2.4 _ Structure in Functions 116
  • 117. Example – formal parameter as a pointer 5/12/2021 2.4 _ Structure in Functions 117
  • 118. 5/12/2021 2.4 _ Structure in Functions 118
  • 119. 5/12/2021 2.4 _ Structure in Functions 119
  • 120. 5/12/2021 2.4 _ Structure in Functions 120
  • 121. Thank you 5/12/2021 2.4 _ Structure in Functions 121
  • 122. UNIT II : DMA, Pointers and Functions, Pointers and Structures By Mr.S.Selvaraj Asst. Professor (SRG) / CSE Kongu Engineering College Perundurai, Erode, Tamilnadu, India Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018. 20CST21 – Programming and Linear Data Structures
  • 123. Unit I : Contents 1. Dynamic Memory Allocation 2. Function pointers 3. Calling a function using a function pointer 4. Structures – Introduction 5. Structures in Functions 6. Pointers to structures 7. Accessing structure members 8. Using pointer as a function argument 9. Array of structures 10. Self referential structures. 5/12/2021 123 2.6 _ Pointers to Structures
  • 124. Pointers to structures • A pointer to a structure must be defined before it is pointed to a structure variable. struct rectangle { short length; short width; } rect1 = {10, 20}; struct rectangle *p; //Creates pointer p p = &rect1; //p points to rect1 5/12/2021 2.6 _ Pointers to Structures 124
  • 125. Accessing structure members • The structure members can be accessed in three ways. • Two of them use a pointer with standard and special notation. – rect1.length //The standard access mechanism that doesn’t use a pointer. – p->length //Uses a special operator, ->, that works only with structures. It uses a pointer. – (*p).length //Pointer dereferenced with * and then connected to the member. It uses a pointer. • Example: 5/12/2021 2.6 _ Pointers to Structures 125
  • 126. Example Program #include <stdio.h> #include <string.h> int main(void) { struct employee { short id; char name[30]; int pay; } emp = {1024, “Steve Wozniak”, 10000}, *p; p = &emp; printf(“Emp-id: %hd, Name: %s, Pay: %dn”, emp.id, (*p).name, p->pay); (*p).id = 4201; /* Updates id */ strcpy(p->name, “Steve Jobs”); /* Updates name */ p->pay = 20000; /* Updates pay */ printf(“Emp-id: %hd, Name: %s, Pay: %dn”, p->id, p->name, p->pay); return 0; } 5/12/2021 2.6 _ Pointers to Structures 126
  • 127. Using a Pointer as a Function Argument • A structure variable can be passed as function arguments. • This will behave as pass-by-value. • This mechanism is safe and it protects the original structure from modification by the function. • However, large structures can consume a lot of memory, so we may need to pass a pointer to a structure instead of the entire structure. • Updating a member’s value using a pointer represents a memory-efficient technique because the function copies not the structure (36 bytes) but its pointer (4 bytes). 5/12/2021 2.6 _ Pointers to Structures 127
  • 128. Example Program /* update_pay.c: Uses a pointer to a structure as a function argument to update the structure. */ #include <stdio.h> struct employee { short id; char name[30]; int pay; } emp = {1024, “Steve Wozniak”, 10000}; void update_pay(struct employee *f_emp, int f_pay); int main(void) { printf(“Old pay = %dn”, emp.pay); update_pay(&emp, 20000); printf(“New pay = %dn”, emp.pay); return 0; } 5/12/2021 2.6 _ Pointers to Structures 128
  • 129. Example Program void update_pay(struct employee *f_emp, int f_pay) { f_emp->pay = f_pay; /* Updates member pay of emp */ } OUTPUT: Old pay = 10000 New pay = 20000 5/12/2021 2.6 _ Pointers to Structures 129
  • 130. Thank you 5/12/2021 2.6 _ Pointers to Structures 130
  • 131. UNIT II : DMA, Pointers and Functions, Pointers and Structures By Mr.S.Selvaraj Asst. Professor (SRG) / CSE Kongu Engineering College Perundurai, Erode, Tamilnadu, India Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018. 20CST21 – Programming and Linear Data Structures
  • 132. Unit I : Contents 1. Dynamic Memory Allocation 2. Function pointers 3. Calling a function using a function pointer 4. Structures – Introduction 5. Structures in Functions 6. Pointers to structures 7. Accessing structure members 8. Using pointer as a function argument 9. Array of structures 10. Self referential structures 5/12/2021 132 2.6 _ Array of Structure and Self Referential Structures
  • 133. Arrays Of Structures • An array of structures is a collection of structures and therefore, each element of an array is of same structure type. • If the user needs to store more than one record of same structure type, we have to create an array of structure. 5/12/2021 2.6 _ Array of Structure and Self Referential Structures 133
  • 134. Arrays Of Structures • Suppose, to handle two students data we can use the two structure variables, stud1 and stud2. • This technique won’t work with 500 students. • C supports an array of structures, whose definition may or may not be combined with the declaration of the structure. • The following statement defines an array of type struct student that can hold 50 sets (or records) of student data. 5/12/2021 2.6 _ Array of Structure and Self Referential Structures 134
  • 135. Syntax for declaring structure array and accessing member 5/12/2021 2.6 _ Array of Structure and Self Referential Structures 135
  • 136. Arrays Of Structures • Alternatively, you can separate the declaration and definition. • You can also use typedef to replace struct student with STUDENT. 5/12/2021 2.6 _ Array of Structure and Self Referential Structures 136
  • 137. Array of Structures • This array can be partially or fully initialized by enclosing the initializers for each array element in a set of curly braces. • Each set is separated from its adjacent one by a comma, while the entire set of initializers are enclosed by outermost braces: 5/12/2021 2.6 _ Array of Structure and Self Referential Structures 137
  • 138. Array of Structures • Each member of each element of this array is accessed by using a dot to connect the member to its array element. • You can use scanf to input values to each member using pointers to these variables (like &stud[i].marks). • A simple for loop using the array index as the key variable prints the entire list. 5/12/2021 2.6 _ Array of Structure and Self Referential Structures 138
  • 139. Example 5/12/2021 2.6 _ Array of Structure and Self Referential Structures 139
  • 140. 5/12/2021 2.6 _ Array of Structure and Self Referential Structures 140
  • 141. Self Referential Structures • Self Referential structures are structures that have one or more pointers which point to the same type of structure, as their member. • In other words, structures pointing to the same type of structures are self-referential in nature. 5/12/2021 2.6 _ Array of Structure and Self Referential Structures 141
  • 142. Self Referential Structures 5/12/2021 2.6 _ Array of Structure and Self Referential Structures 142
  • 143. Example • In the above example ‘link’ is a pointer to a structure of type ‘node’. • Hence, the structure ‘node’ is a self-referential structure with ‘link’ as the referencing pointer. • An important point to consider is that the pointer should be initialized properly before accessing, as by default it contains garbage value. 5/12/2021 2.6 _ Array of Structure and Self Referential Structures 143
  • 144. Types of Self Referential Structures • Self Referential Structure with Single Link • Self Referential Structure with Multiple Links 5/12/2021 2.6 _ Array of Structure and Self Referential Structures 144
  • 145. Self Referential Structure with Single Link • These structures can have only one self- pointer as their member. • The following example will show us how to connect the objects of a self-referential structure with the single link and access the corresponding data members. • The connection formed is shown in the following figure. 5/12/2021 2.6 _ Array of Structure and Self Referential Structures 145
  • 146. Example 5/12/2021 2.6 _ Array of Structure and Self Referential Structures 146
  • 147. 5/12/2021 2.6 _ Array of Structure and Self Referential Structures 147 10 20 X 30 40 X
  • 148. Self Referential Structure with Multiple Link • Self referential structures with multiple links can have more than one self-pointers. • Many complicated data structures can be easily constructed using these structures. • Such structures can easily connect to more than one nodes at a time. • The following example shows one such structure with more than one links. • The connections made in the above example can be understood using the following figure. 5/12/2021 2.6 _ Array of Structure and Self Referential Structures 148
  • 149. Example 5/12/2021 2.6 _ Array of Structure and Self Referential Structures 149 X 10 X X 20 X X 30 X
  • 150. 5/12/2021 2.6 _ Array of Structure and Self Referential Structures 150
  • 151. Applications of Self Referential Structures • Self referential structures are very useful in creation of other complex data structures like: – Linked Lists – Stacks – Queues – Trees – Graphs etc 5/12/2021 2.6 _ Array of Structure and Self Referential Structures 151
  • 152. Thank you 5/12/2021 2.6 _ Array of Structure and Self Referential Structures 152