Pointers and Dynamic
Memory Allocations
1Presented by: Group-E (The Anonymous)
Bikash Dhakal
Bimal Pradhan
Gagan Puri
Bikram Bhurtel
Rabin BK
Introduction to pointers
Declaration of pointer
Accessing a variable through pointer
Chain of pointers
Pointer expression
Pointers and Array
Pointer to function
Pointer to structure
Trouble with pointers
Memory allocation
Dynamic Memory Allocation
Refrences
2
3
Computer use their memory for storing instructions of the
programs.
Pointers are more efficient in handling arrays and data types
It allows C to support dynamic memory management
It reduces length and complexity of programs
Pointer Declaration
4
Pointer is a variable which can hold the address of a
memory location
The value stored in a pointer type variable is interpreted
as an address
Pointer
It contain address that belongs to separate data type
It can be declared just like any other variables
It takes the following form:
data_type *pointer_name;
The above statement tells the compiler three things above the
variables pointer_name
5
Pointer Declaration
1. The asterisk(*) tells that the variables pt_name is a pointer variable.
2. pt_name needs a memory location.
3. pt_name points to a variable of type data type.
Example:
Pointer declaration Interpretation
Int *rollnumber; Create a pointer variables rollnumber capable of pointing to an integer type
variable or capable of holding the address of an integer type variable
Char *name; Create a pointer variable name capable of pointing to a character type variable
or capable of holding the address of a character type
Float *salary; Create a pointer variable salary capable of pointing to a float type variable or
capable of holding the address of a float type variable
6
The process of assigning the address of a variables to a pointer variable
called initialization
As pointer out earlier, all uninitialized pointers will have same unknown
values that will be interpreted as memory address
It takes the following form:
datatype*pointer_name = & ordinary_variabl e_name
7
Initialization of Pointer variables
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int x, *p;
printf("Enter a number: ");
scanf("%d",&x);
p = &x;
printf("n value of x=%d",*p);
printf("n Address of x using pointer = %u",p);
printf("n Address of x using & pointer = %u",&x);
getch();
}
8
Unary operator also known as indirect operator * (asterick) used to access the
value of variable using pointer.
data_type *p=& ordinary_variable_name
eg :- int quantity ,*p , n
quantity =123;
p=&quantity;
n=*p;
#include<stdio.h>
#include<conio.h>
void main()
{
int x, *p;
printf("Enter a number: ");
scanf("%d",&x);
p = &x;
printf("n value of x=%d",*p);
printf("n Address of x using pointer = %u",p);
printf("n Address of x using & pointer = %u",&x);
getch();
}
9
Accessing a variable through its pointer
 Chain of pointer can be created by pointing a pointer to another pointer.
P₂ P₁ variable
 Here pointer variable P₂ contains the address of the pointer variable P₁ , which
points to the location that contains the desire value .
 also known as multiple indirections operators.
Address 2 Address 1 value
10
Chain of pointers
void main()
{
int x,*p1,**p2;
x=100;
p1=&x;
p2=p1;
printf(“%d”,**p2);
}
11
 Pointer variables can be used in expression.
 C allows us to add integers to or subtract integers from pointer , as well as allows
to subtract one from another.
like , p1+p2 , p1-p2 etc
 Two pointers can also be compared using the relational operators .
like , p1>p2 , p1==p2 etc
 However pointer cannot be use in multiple or division and also cannot be added.
12
Pointer expression
Syntax:
data_type *pointer_name[size]
Example:-
void main()
{
int *p[3]
int a=2, b=3, c=4;
p[0]=&a;
p[1]=&b;
p[2]=&c;
for(i=0;i<3;i++)
{
printf (“value =%d”,*p[i])
}
} 13
Pointers and Array
→ ARRAY OF POINTER
 Array name itself is a pointer that points to it’s zeroth element
Example:-
int a[5]
the array name a → &a[0]
 When the pointer a is incremented by 1
it gives address of oneth element and so on
i.e. a+1→ &a[1]
a+2→ &a[2]
a+i→ &a[i]
Thus *(a+i)→ a[i]
Example :-
void main()
{
int a[2],i;
printf(“input array
elements:”);
for (i=0;i<5;i++)
{
scanf(“%d”,a+1);
}
printf(”n array elements
are:”);
for (i=0;i<5;i++)
{
printf(“%dt”,*(a+i));
}
}
Relation between Array and Pointers
14
Pointer and string
Strings are character arrays
for string syntax
char str[6]=”hello” → null character at the end of string
but in pointer to string
char *str = ”hello”
char *cards[ 4 ] = {"Hearts", "Diamonds",
"Clubs",”spades” }; → here it represents
that the strings are not in the array, only pointers to the strings are in the array
15
 Call by reference method is used
 The address of data items is passed to the function
 Data items can be altered globally from within the function
Pointer to a Function
16
Example:
#include<stdio.h>
void swap (int*p, int*q);
int main()
{
int x,y;
x=50;
y=70;
printf("nValue of x and y before swap are :
%dt%d",x,y);
swap(&x,&y);
printf ("Values of x and y after swap are:
%dt%d",x,y);
return 0;
}
void swap(int*p, int*q)
{
int temp;
temp=*p;
*p=*q;
*q=temp;
}
Values of x and y before swap are : 50 70
Values of x and y after swap are : 70 50
17
 pointers pointing to a struct are known as "Structure Pointers"
 address of a structure variable is assigned to the pointer
variable
 pointer variables which stores address of structure must be
declared as pointer to structure
18
Pointer to structure
#include <stdio.h>
#include <conio.h>
struct employee
{
char name [20];
int id;
float salary;
};
void main()
{
struct employee e1 ={"John",201,10000.50};
struct employee *e;
e=&e1;
printf("n%st%dt%.2f",e->name,e->id,e->salary);
getch();
} 19
20
Trouble with Pointers
 Compiler may not detect the error and produce unnecessary
results
 Debugging becomes difficult
 Some common errors
int *p, m=100;
p=m;
p=&m;
printf(“%d”,p);
21
Types of memory allocation
Fixed in size
Automatic memory allocation
space is automatically determined
E.g: int a =10; (2 bytes space is occupied in memory)
Static Memory Allocation (SMA)
Fixed in size
Done at compile time only
Cannot take data more than the allocated size
E.g: char mem_alloc[12];
int a[5]={1,6,9,4,11};
Often real world problems meaning that, required storage space
changes over time
Size can be changed
Done at run time
We can allocate (create) and deallocate (free/delete) storage space
whenever needed
We can always have exact amount of storage space (no more, no less)
There are 4 library functions that come into action for the DMA:
malloc()
calloc()
realloc()
free() 22
Dynamic Memory Allocation (DMA)
Syntax:
m=(cast-type*)malloc(size-in-bytes)
Reserves a (single) block of memory of specified size in bytes
Returns a pointer of void type to the first byte of the space which is
allocated
23
malloc()
E.g:
a=(int*)malloc(10*sizeof(int));
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int *a,i;
float num;
printf("Enter size for memory allocation: ");
scanf("%f",&num);
a=(int*)malloc(sizeof(num));
printf("Allocated memory is: ");
for(i = 0; i < num; ++i)
{
printf("%ut",a+i);
}
free(a);
getch();
} 24
calloc()
Syntax:
m=(cast-type*)calloc(n,element-size)
Reserves multiple block of memory each of same size and sets all
bytes to zero
The difference in malloc and calloc is that malloc does not set the
memory to zero where as calloc sets allocated memory to zero.
25
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int *a,i;
float num;
printf("Enter size for memory allocation: ");
scanf("%f",&num);
a=(int*)calloc(num,sizeof(int));
printf("Allocated memory is: ");
for(i = 0; i < num; ++i)
{
printf("%ut",a+i);
}
free(a);
getch();
} 26
realloc()
Syntax:
m= (int*) malloc(size from the user);
-------------------
m=(cast-type*)realloc(n, new-size)
Used to increase or decrease the allocated memory size using malloc()
or calloc() functions
It adjusts the old memory region if the new size is smaller than the
size of old memory
If the new size is larger than the existing memory size, it increases the
size by copying the contents of old memory region to new memory
region
27
#include <stdlib.h>
void main()
{
int *ptr, i , n1, n2;
printf("Enter size of array: ");
scanf("%d", &n1);
ptr = (int*) malloc(n1*sizeof(int));
printf("Address of previously allocated memory: ");
for(i = 0; i < n1; ++i)
{
printf("%ut",ptr + i);
}
printf("nEnter new size of array: ");
scanf("%d", &n2);
ptr = (int*) realloc(ptr, n2);
for(i = 0; i < n2; ++i)
{
printf("%ut", ptr + i);
}
getch();
}
28
References:
Websites:
google.com
codecadamy.com
tutorialspoint.com
External sources:
Text book: Programming in ANSIC (E-Balagurusamy)
29
Queries
30

Pointers and Dynamic Memory Allocation

  • 1.
    Pointers and Dynamic MemoryAllocations 1Presented by: Group-E (The Anonymous) Bikash Dhakal Bimal Pradhan Gagan Puri Bikram Bhurtel Rabin BK
  • 2.
    Introduction to pointers Declarationof pointer Accessing a variable through pointer Chain of pointers Pointer expression Pointers and Array Pointer to function Pointer to structure Trouble with pointers Memory allocation Dynamic Memory Allocation Refrences 2
  • 3.
    3 Computer use theirmemory for storing instructions of the programs. Pointers are more efficient in handling arrays and data types It allows C to support dynamic memory management It reduces length and complexity of programs Pointer Declaration
  • 4.
    4 Pointer is avariable which can hold the address of a memory location The value stored in a pointer type variable is interpreted as an address Pointer
  • 5.
    It contain addressthat belongs to separate data type It can be declared just like any other variables It takes the following form: data_type *pointer_name; The above statement tells the compiler three things above the variables pointer_name 5 Pointer Declaration
  • 6.
    1. The asterisk(*)tells that the variables pt_name is a pointer variable. 2. pt_name needs a memory location. 3. pt_name points to a variable of type data type. Example: Pointer declaration Interpretation Int *rollnumber; Create a pointer variables rollnumber capable of pointing to an integer type variable or capable of holding the address of an integer type variable Char *name; Create a pointer variable name capable of pointing to a character type variable or capable of holding the address of a character type Float *salary; Create a pointer variable salary capable of pointing to a float type variable or capable of holding the address of a float type variable 6
  • 7.
    The process ofassigning the address of a variables to a pointer variable called initialization As pointer out earlier, all uninitialized pointers will have same unknown values that will be interpreted as memory address It takes the following form: datatype*pointer_name = & ordinary_variabl e_name 7 Initialization of Pointer variables
  • 8.
    Example: #include<stdio.h> #include<conio.h> void main() { int x,*p; printf("Enter a number: "); scanf("%d",&x); p = &x; printf("n value of x=%d",*p); printf("n Address of x using pointer = %u",p); printf("n Address of x using & pointer = %u",&x); getch(); } 8
  • 9.
    Unary operator alsoknown as indirect operator * (asterick) used to access the value of variable using pointer. data_type *p=& ordinary_variable_name eg :- int quantity ,*p , n quantity =123; p=&quantity; n=*p; #include<stdio.h> #include<conio.h> void main() { int x, *p; printf("Enter a number: "); scanf("%d",&x); p = &x; printf("n value of x=%d",*p); printf("n Address of x using pointer = %u",p); printf("n Address of x using & pointer = %u",&x); getch(); } 9 Accessing a variable through its pointer
  • 10.
     Chain ofpointer can be created by pointing a pointer to another pointer. P₂ P₁ variable  Here pointer variable P₂ contains the address of the pointer variable P₁ , which points to the location that contains the desire value .  also known as multiple indirections operators. Address 2 Address 1 value 10 Chain of pointers
  • 11.
  • 12.
     Pointer variablescan be used in expression.  C allows us to add integers to or subtract integers from pointer , as well as allows to subtract one from another. like , p1+p2 , p1-p2 etc  Two pointers can also be compared using the relational operators . like , p1>p2 , p1==p2 etc  However pointer cannot be use in multiple or division and also cannot be added. 12 Pointer expression
  • 13.
    Syntax: data_type *pointer_name[size] Example:- void main() { int*p[3] int a=2, b=3, c=4; p[0]=&a; p[1]=&b; p[2]=&c; for(i=0;i<3;i++) { printf (“value =%d”,*p[i]) } } 13 Pointers and Array → ARRAY OF POINTER
  • 14.
     Array nameitself is a pointer that points to it’s zeroth element Example:- int a[5] the array name a → &a[0]  When the pointer a is incremented by 1 it gives address of oneth element and so on i.e. a+1→ &a[1] a+2→ &a[2] a+i→ &a[i] Thus *(a+i)→ a[i] Example :- void main() { int a[2],i; printf(“input array elements:”); for (i=0;i<5;i++) { scanf(“%d”,a+1); } printf(”n array elements are:”); for (i=0;i<5;i++) { printf(“%dt”,*(a+i)); } } Relation between Array and Pointers 14
  • 15.
    Pointer and string Stringsare character arrays for string syntax char str[6]=”hello” → null character at the end of string but in pointer to string char *str = ”hello” char *cards[ 4 ] = {"Hearts", "Diamonds", "Clubs",”spades” }; → here it represents that the strings are not in the array, only pointers to the strings are in the array 15
  • 16.
     Call byreference method is used  The address of data items is passed to the function  Data items can be altered globally from within the function Pointer to a Function 16
  • 17.
    Example: #include<stdio.h> void swap (int*p,int*q); int main() { int x,y; x=50; y=70; printf("nValue of x and y before swap are : %dt%d",x,y); swap(&x,&y); printf ("Values of x and y after swap are: %dt%d",x,y); return 0; } void swap(int*p, int*q) { int temp; temp=*p; *p=*q; *q=temp; } Values of x and y before swap are : 50 70 Values of x and y after swap are : 70 50 17
  • 18.
     pointers pointingto a struct are known as "Structure Pointers"  address of a structure variable is assigned to the pointer variable  pointer variables which stores address of structure must be declared as pointer to structure 18 Pointer to structure
  • 19.
    #include <stdio.h> #include <conio.h> structemployee { char name [20]; int id; float salary; }; void main() { struct employee e1 ={"John",201,10000.50}; struct employee *e; e=&e1; printf("n%st%dt%.2f",e->name,e->id,e->salary); getch(); } 19
  • 20.
    20 Trouble with Pointers Compiler may not detect the error and produce unnecessary results  Debugging becomes difficult  Some common errors int *p, m=100; p=m; p=&m; printf(“%d”,p);
  • 21.
    21 Types of memoryallocation Fixed in size Automatic memory allocation space is automatically determined E.g: int a =10; (2 bytes space is occupied in memory) Static Memory Allocation (SMA) Fixed in size Done at compile time only Cannot take data more than the allocated size E.g: char mem_alloc[12]; int a[5]={1,6,9,4,11};
  • 22.
    Often real worldproblems meaning that, required storage space changes over time Size can be changed Done at run time We can allocate (create) and deallocate (free/delete) storage space whenever needed We can always have exact amount of storage space (no more, no less) There are 4 library functions that come into action for the DMA: malloc() calloc() realloc() free() 22 Dynamic Memory Allocation (DMA)
  • 23.
    Syntax: m=(cast-type*)malloc(size-in-bytes) Reserves a (single)block of memory of specified size in bytes Returns a pointer of void type to the first byte of the space which is allocated 23 malloc() E.g: a=(int*)malloc(10*sizeof(int));
  • 24.
    #include<stdio.h> #include<conio.h> #include<stdlib.h> void main() { int *a,i; floatnum; printf("Enter size for memory allocation: "); scanf("%f",&num); a=(int*)malloc(sizeof(num)); printf("Allocated memory is: "); for(i = 0; i < num; ++i) { printf("%ut",a+i); } free(a); getch(); } 24
  • 25.
    calloc() Syntax: m=(cast-type*)calloc(n,element-size) Reserves multiple blockof memory each of same size and sets all bytes to zero The difference in malloc and calloc is that malloc does not set the memory to zero where as calloc sets allocated memory to zero. 25
  • 26.
    #include<stdio.h> #include<conio.h> #include<stdlib.h> void main() { int *a,i; floatnum; printf("Enter size for memory allocation: "); scanf("%f",&num); a=(int*)calloc(num,sizeof(int)); printf("Allocated memory is: "); for(i = 0; i < num; ++i) { printf("%ut",a+i); } free(a); getch(); } 26
  • 27.
    realloc() Syntax: m= (int*) malloc(sizefrom the user); ------------------- m=(cast-type*)realloc(n, new-size) Used to increase or decrease the allocated memory size using malloc() or calloc() functions It adjusts the old memory region if the new size is smaller than the size of old memory If the new size is larger than the existing memory size, it increases the size by copying the contents of old memory region to new memory region 27
  • 28.
    #include <stdlib.h> void main() { int*ptr, i , n1, n2; printf("Enter size of array: "); scanf("%d", &n1); ptr = (int*) malloc(n1*sizeof(int)); printf("Address of previously allocated memory: "); for(i = 0; i < n1; ++i) { printf("%ut",ptr + i); } printf("nEnter new size of array: "); scanf("%d", &n2); ptr = (int*) realloc(ptr, n2); for(i = 0; i < n2; ++i) { printf("%ut", ptr + i); } getch(); } 28
  • 29.
  • 30.