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

Module 3 - Pointers & Dynamic Memory Allocation

Uploaded by

balram.2022
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Module 3 - Pointers & Dynamic Memory Allocation

Uploaded by

balram.2022
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 30

Pointer

What is Pointer?
 A normal variable is used to store value.
 A pointer is a variable that store address / reference of another variable.
 Pointer is derived data type in C language.
 A pointer contains the memory address of that variable as their value.
Pointers are also called address variables because they contain the
addresses of other variables.
Declaration & Initialization of Pointer
Outpu
Syntax
t
1 datatype 10 10 5000
*ptr_variablename;
Exampl
e
1 void main()
2 { Variable Value Address
3 int a=10, *p; // assign memory address
4 of a to pointer variable p a 10 5000
5 p = &a;
6 printf("%d %d %d", a, *p, p); p 5048
7 }
5000

 p is integer pointer variable


 & is address of or referencing operator which returns memory address of
variable.
 * is indirection or dereferencing operator which returns value stored at that
memory address.
 & operator is the inverse of * operator
 x = a is same as x = *(&a)
Why use Pointer?
 C uses pointers to create dynamic data structures, data structures built
up from blocks of memory allocated from the heap at run-time.
Example linked list, tree, etc.
 C uses pointers to handle variable parameters passed to functions.
 Pointers in C provide an alternative way to access information stored in
arrays.
 Pointer use in system level programming where memory addresses are
useful. For example shared memory used by multiple threads.
 Pointers are used for file handling.
 This is the reason why C is versatile.
Pointer to Pointer – Double Pointer
 Pointer holds the address of another variable of same type.
 When a pointer holds the address of another pointer then such type of
pointer is known as pointer-to-pointer or double pointer.
 The first pointer contains the address of the second pointer, which points
to the location that contains the actual value.
Syntax
Pointer Pointer Variable
1 datatype
**ptr_variablename;
addres addres value
Exampl s s
e
1 int **ptr;
Write a program to print variable, address of pointer variable and pointer to pointer
variable.

WAP to print Odd numbers between 1 to n


Program
1 #include <stdio.h>
2 int main () {
3 int var;
4 int *ptr;
5 int **pptr;
6 var = 3000;
7 ptr = &var; // address of var
8 pptr = &ptr; // address of ptr using address of operator &
9 printf("Value of var = %d\n", var );
10 printf("Value available at *ptr = %d\n", *ptr );
11 printf("Value available at **pptr = %d\n", **pptr);
12 return 0;
13 }

Outpu
t
Value of var = 3000
Value available at *ptr = 3000
Value available at **pptr = 3000

Prof. Nilesh Gambhava #3110003 (PPS) – Pointer 6


Relation between Array & Pointer
 When we declare an array, compiler allocates continuous blocks of
memory so that all the elements of an array can be stored in that
memory.
 The address of first allocated byte or the address of first element is
assigned to an array name.
 Thus array name works as pointer variable.
 The address of first element is also known as base address.
Relation between Array & Pointer – Cont.
 Example: int a[10], *p;
 a[0] is same as *(a+0), a[2] is same as *(a+2) and a[i] is same as *(a+i)

a: a[0] a: *(a+0) 2000

a[1] a+1: *(a+1) 2002


. .
. .
. .
. .
a[i] a+i: *(a+i) 2000 +
. . i*2
. .
. .
. .
a[9] a+9: *(a+9) 2018
Array of Pointer
 As we have an array of char, int, float etc, same way we can have an
array of pointer.
 Individual elements of an array will store the address values.
 So, an array is a collection of values of similar type. It can also be a
collection of references of similar type known by single name.
Syntax
1 datatype *name[size];

Exampl
e
1 int *ptr[5]; //declares an array of integer pointer of size 5
Array of Pointer – Cont.
 An array of pointers ptr can be used to point to different rows of matrix
as follow:
Exampl
e
1 for(i=0; i<5; i++)
2 {
3 ptr[i]=&mat[i][0];
4 }

ptr 0 1 2
ptr[0]
ptr[1]
ptr[2]
ptr[3]
ptr[4]
Write a program to swap value of two variables using pointer / call by reference.

WAP to print Odd numbers between 1 to n


Program
1 int main()
2 {
3 int num1,num2;
4 printf("Enter value of num1 and num2: ");
5 scanf("%d %d",&num1, &num2);
6
7 //displaying numbers before swapping
8 printf("Before Swapping: num1 is: %d, num2 is: %d\n",num1,num2);
9
10 //calling the user defined function swap()
11 swap(&num1,&num2);
12
13 //displaying numbers after swapping
14 printf("After Swapping: num1 is: %d, num2 is: %d\n",num1,num2);
15 return 0;
16 }
Outpu
t
Enter value of num1 and num2: 5
10
Before Swapping: num1 is: 5, num2 is:
10
After Swapping: num1 is: 10, num2
is: 5 Nilesh Gambhava
Prof. #3110003 (PPS) – Pointer 11
Pointer and Function
 Like normal variable, pointer variable can be passed as function
argument and function can return pointer as well.
 There are two approaches to passing argument to a function:
 Call by value
 Call by reference / address
Call by Value
 In this approach, the values are passed as function argument to the
definition of function.
Program Output
1 #include<stdio.h> Values before calling 10, 20
2 void fun(int,int); Values after calling 10, 20
3 int main()
4 {
5 int A=10,B=20;
6 printf("\nValues before calling %d, %d",A,B);
7 fun(A,B); Addre 4825 2468
8 printf("\nValues after calling %d, %d",A,B); ss 2 8
9 return 0; Valu 10 20 1011 2022
e
10 }
11 void fun(int X,int Y) Variabl A B X Y
e
12 {
13 X=11;
14 Y=22;
15 }
Call by Reference / Address
 In this approach, the references / addresses are passed as function
argument to the definition of function.
Program
Output
1 #include<stdio.h>
Values before calling 10, 20
2 void fun(int*,int*); Values after calling 11, 22
3 int main()
4 {
5 int A=10,B=20;
6 printf("\nValues before calling %d, %d",A,B);
7 fun(&A,&B); Addre 2468
4825
8 printf("\nValues after calling %d, %d",A,B); ss 2 11 8 4825 2468
9 return 0; Value 10 2022
2 8
10 }
11 void fun(int *X,int *Y) Variabl A B *X *Y
12 { e
13 *X=11;
14 *Y=22;
15 }
Pointer to Function
 Every function has reference or address, and if we know the reference or
address of function, we can access the function using its reference or
address.
 This is the way of accessing function using pointer.
Syntax
1 return-type (*ptr-function)(argument
list);

 return-type: Type of value function will return.


 argument list: Represents the type and number of value function will
take, values are sent by the calling statement.
 (*ptr-function): The parentheses around *ptr-function tells the compiler
that it is pointer to function.
 If we write *ptr-function without parentheses then it tells the compiler
that ptr-function is a function that will return a pointer.
Write a program to sum of two numbers using pointer to function.

WAP to print Odd numbers between 1 to n


Program
Outpu
1 #include<stdio.h>
t
2 int Sum(int,int); Enter 1st number : 5
3 int (*ptr)(int,int);
4 int main() Enter 2nd number : 10
5 {
6 int a,b,rt; The sum is : 15
7 printf("\nEnter 1st number : ");
8 scanf("%d",&a);
9 printf("\nEnter 2nd number : ");
10 scanf("%d",&b);
11 ptr = Sum;
12 rt = (*ptr)(a,b);
13 printf("\nThe sum is : %d",rt);
14 return 0;
15 }
16 int Sum(int x,int y)
17 {
18 return x + y;
19 }

Prof. Nilesh Gambhava #3110003 (PPS) – Pointer 16


Practice Programs
1. Write a C program to print the address of variable using pointer.
2. Write a C a program to swap two elements using pointer.
3. Write a C a program to print value and address of a variable
4. Write a C a program to calculate sum of two numbers using pointer
5. Write a C a program to swap value of two numbers using pointer
6. Write a C a program to calculate sum of elements of an array using pointer
7. Write a C a program to swap value of two variables using function
8. Write a C a program to print the address of character and the character of string using pointer
9. Write a C a program for sorting using pointer
Dynamic
Memory
Allocation
Dynamic Memory Allocation (DMA)
 If memory is allocated at runtime (during execution of program) then it
is called dynamic memory.
 It allocates memory from heap (heap: it is an empty area in memory)
 Memory can be accessed only through a pointer.

When DMA is needed?


 It is used when number of variables are not known in advance or large in
size.
 Memory can be allocated at any time and can be released at any time
during runtime.
malloc() function
 malloc () is used to allocate a fixed amount of memory during the
execution of a program.
 malloc () allocates size_in_bytes of memory from heap, if the
allocation succeeds, a pointer to the block of memory is returned else
NULL is returned.
 Allocated memory space may not be contiguous.
 Each block contains a size, a pointer to the next block, and the space
itself.
 The blocks are kept in ascending order of storage address, and the last
block points to the first.
Syntax Description
 The memory is not initialized.
ptr_var = (cast_type This statement returns a pointer to size_in_bytes of
*) malloc uninitialized storage, or NULL if the request cannot be satisfied.
(size_in_bytes);
Example: fp = (int *)malloc(sizeof(int) *20);
Write a C program to allocate memory using
malloc.
Program
1 #include <stdio.h>
2 void main()
3 {
4 int *fp; //fp is a pointer variable
5 fp = (int *)malloc(sizeof(int)); //
6 returns a pointer to int size storage
7 *fp = 25; //store 25 in the address pointed by fp
8 printf("%d", *fp); //print the value of fp, i.e. 25
9 free(fp); //free up the space pointed to by fp
}

Output
25
calloc() function
 calloc() is used to allocate a block of memory during the execution of
a program
 calloc() allocates a region of memory to hold no_of_blocks of
size_of_block each, if the allocation succeeds then a pointer to the
block of memory is returned else NULL is returned.
 The memory is initialized to ZERO.

Syntax Description
ptr_var = (cast_type This statement returns a pointer to no_of_blocks of size
*) calloc size_of_blocks, it returns NULL if the request cannot be
(no_of_blocks, satisfied.
size_of_block);
Example:
int n = 20;
fp = (int *)calloc(n, sizeof(int));
Write a C program to allocate memory using
calloc.
Program
1 #include <stdio.h>
2 void main()
3 {
4 int i, n; //i, n are integer variables
5 int *fp; //fp is a pointer variable
6 printf("Enter how many numbers: ");
7 scanf("%d", &n);
8 fp = (int *)calloc(n, sizeof(int)); //
9 calloc returns a pointer to n blocks
10 for(i = 0; i < n; i++) //loop through until all the blocks are read
11 {
12 scanf("%d",&fp[i]); //read and store into location where fp points
13
14 }
free(fp); //frees the space pointed to by fp
}
realloc() function
 realloc() changes the size of the object pointed to by pointer fp to
specified size.
 The contents will be unchanged up to the minimum of the old and new
sizes.
 If the new size is larger, the new space will be uninitialized.
 realloc() returns a pointer to the new space, or NULL if the request
cannot be satisfied, in which case *fp is unchanged.
Syntax Description
ptr_var = (cast_type This statement returns a pointer to new space, or NULL if the
*) realloc (void *fp, request cannot be satisfied.
size_t);
Example: fp = (int *)realloc(fp,sizeof(int)*20);
Write a C program to allocate memory using
realloc.
Program
1 #include <stdio.h>
2 void main()
3 {
4 int *fp; //fp is a file pointer
5 fp = (int *)malloc(sizeof(int)); //
6 malloc returns a pointer to int size storage
7 *fp = 25; //store 25 in the address pointed by fp
8 fp =(int *)realloc(fp, 2*sizeof(int)); //returns a pointer to new space
9 printf("%d", *fp); //print the value of fp
free(fp); //free up the space pointed to by fp
}

Output
25
free() function
 free deallocates the space pointed to by fp.
 It does nothing if fp is NULL.
 fp must be a pointer to space previously allocated by calloc, malloc or
realloc.

Syntax Description
void free(void *); This statement free up the memory not needed anymore.

Example: free(fp);
Write a C program to sort numbers using malloc
Program
Program
(cont.)
1 #include<stdio.h> 17 if(p[i] > p[j])
2 #include<stdlib.h> 18 {
3 void main() 19 t = p[i];
4 { 20 p[i] = p[j];
5 int i,j,t,n; 21 p[j] = t;
6 int *p; 22 }
7 printf("Enter value of n: "); 23 }
8 scanf("%d", &n); 24 }
9 p=(int *) malloc(n * sizeof(int)); 25 printf("Ascending order\n");
10 printf("Enter values\n"); 26 for(i=0; i<n; i++)
11 for(i=0; i<n; i++) 27 printf("%d\n", p[i]);
12 scanf("%d", &p[i]); 28 free(p);
13 for(i=0; i<n; i++) 29 }
14 {
15 for(j= i+1; j<n; j++)
16 {
Write a C program to find square of numbers using calloc
Program Output
1 #include<stdio.h> Enter value of n: 3
2 #include<stdlib.h> Enter values
3 void main() 3
4 { 2
5 int i,n; 5
6 int *p; Square of 3 = 9
7 printf("Enter value of n: "); Square of 2 = 4
8 scanf("%d",&n); Square of 5 = 25
9 p=(int*)calloc(n,sizeof(int));
10 printf("Enter values\n");
11 for(i=0;i<n;i++)
12 scanf("%d",&p[i]);
13 for(i=0;i<n;i++)
14 printf("Square of %d = %d\
15 n", p[i], p[i] * p[i]);
16 free(p);
17 }
Write a C program to add/remove item from a list using
realloc
Program
Program
(cont.)
1 #include<stdio.h> 18
2 #include<stdlib.h> 19 printf("Enter new size of list: ");
3 void main() 20 scanf("%d", &n2);
4 { 21
5 int i, n1, n2; 22 fp = realloc(fp, n2 * sizeof(int));
6 int *fp; 23 if(n2 > n1)
7 printf("Enter size of list: "); 24 {
8 scanf("%d", &n1); 25 printf("Enter %d numbers\
9 fp=(int *) malloc (n1 * sizeof(int)); 26 n", n2 - n1);
10 27 for(i = n1; i < n2; i++)
11 printf("Enter %d numbers\n", n1); 28 scanf("%d", &fp[i]);
12 for(i = 0; i < n1; i++) 29 }
13 scanf("%d", &fp[i]); 30 printf("The numbers in the list are\
14 31 n");
15 printf("The numbers in the list are\n"); 32 for(i = 0; i < n2; i++)
16 for(i = 0; i < n1; i++) printf("%d\n", fp[i]);
17 printf("%d\n", fp[i]); }
Practice Programs
1) Write a C program to calculate sum of n numbers entered by user.
2) Write a C program to input and print text using DMA
3) Write a C program to read and print student details using structure and
DMA

You might also like