1
Pointers and Dynamic
Memory Allocations
Content
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
5
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
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
7
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
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();
}
9
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();
}
Accessing a variable through its pointer
10
• 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
Chain of pointers
11
Example
void main()
{
int x,*p1,**p2;
x=100;
p1=&x;
p2=p1;
printf(“%d”,**p2);
}
12
• 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.
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])
}
}
Pointers and Array
→ ARRAY OF POINTER
14
 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(“%d
t”,*(a+i));
}
}
Relation between Array and Pointers
15
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
16

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
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
18

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
Pointer to structure
19
//Program to pass the address of a structure variable to a function
#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();
}
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};
22
• 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()
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
malloc()
E.g:
a=(int*)malloc(10*sizeof(int));
24
#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();
}
25
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.
26
#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();
}
27
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
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: ");
29
References:
Websites:
• google.com
• codecadamy.com
• tutorialspoint.com
External sources:
Text book: Programming in ANSIC (E-Balagurusamy)