Unit 8 Pointers & Dynamic Memory Allocation

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

C Pointers

The pointer in C language is a variable which stores the address of another variable. This
variable can be of type int, char, array, function, or any other pointer.

The size of the pointer depends on the architecture. However, in 32-bit architecture the
size of a pointer is 2 bytes.

Declaring a pointer
The pointer in c language can be declared using * (asterisk symbol). It is also known as
indirection operator also called dereference operator.

int *a; //pointer to int


char *c; //pointer to char
Eg:-

int n = 10;
int *p ; p=&n // pointer assignment

#include<stdio.h>
int main()
{
int n=50;
int *p;
p=&n;
printf("Address of n variable is %x \n", &n);
printf("value of p variable is %x \n", p);
printf("Value of n using pointer p variable is %d \n",*p);
return 0;
Output
Address of n variable is 65fe14
Value of p variable is 65fe14
Value of n using pointer p variable is 50
}

Note: If we want to find the newly address of pointer then we go for pointer to
pointer concept

Indirection Operator
The indirection operator is an unary operator represented by (*) symbol which is used in
pointer to pointer to a integer, char, array or pointer to an unknown data type

Pointer Arithmetic in C
We can perform arithmetic operations on the pointers like addition, subtraction, etc.
Following arithmetic operations are possible on the pointer in C language:

o Addition / Increment
o Subtraction / Decrement

What can be done


 We add or subtract an integer to/from an address.
 We can subtract two address of same type.

What can’t be done


 We can’t add, multiply or divide two addresses.
 We can’t multiply or divide an integer to an address.
valid
Invalid
int n, m; int n, m;
int *p, *q; int *p, *q;

p+q p+1
p*q p+3
p/q p-q
&a+&p p-2
#include<stdio.h>
int main()
{
int n=50, m=40;
int *p, *q;

p=&n;
q=&m;

printf("Address of p variable is %u \n" ,p);


printf("Address of q variable is %u \n" ,q);
p=p+1;
printf("After Increment: Address of p variable is %u \n" ,p);
return 0;
}
Output
Address of p variable is 6422028
Address of q variable is 6422024
After Increment : Address of p is 6422032

The Rule to increment the pointer is given below:

new_address= current_address + i

Where i is the number by which the pointer get increased.

32-bit
For 32-bit int variable, it will be incremented by 2 bytes.

64-bit
For 64-bit int variable, it will be incremented by 4 bytes.

Pointer as return values


Pointer is a variable which is used to store the memory address of another
variable. We can pass pointers to the function as well as return pointer from a
function.
#include <stdio.h>
int* sum(int *x);
int main ()
{
int a=10,*c;
printf("before calling address of a %d\n", &a) ;
c= sum(&a);
printf("after calling address of c %d", c) ;
return 0;

}
int* sum(int *x)
{
return (x+2);

Using pointer for array processing


We can use pointer for array processing. Manipulating the elements of array by using
pointer is called array processing by pointer.

Example of pointer with single dimensional array

#include <stdio.h>
int main ()
{
int a[5],sum,i,*p;
p=&a[0];
printf("Enter array element\n");

for(i=0;i<5;i++)
{
scanf("%d",p+i);
}

printf("the array element are :");


for(i=0;i<5;i++)
{
sum=sum + *(p+i);

}
printf("%d", sum);
return 0;

Pointer with multi-dimensional Array


#include <stdio.h>
int main ()
{
int a[3][4],sum,i,j,*p;
p=&a[0][0];
printf("Enter array element\n");

for(i=0;i<3;i++)
{
for(j=0;j<4;j++)
{
scanf("%d",p+i);
}
}

printf("the array element are :");

for(i=0;i<3;i++)
{
for(j=0;j<4;j++)
{
sum=sum + *(p+i);
}
}
printf("%d", sum);
return 0;
}
Pointer and String
We have used pointers with the array, functions, and primitive data types so far. However,
pointers can be used to point to the strings.

#include<stdio.h>
void main ()
{
char *p,str[20]="hello Kathmandu";
p=&str[0] ;
while(*p!='\0')
{
printf("%c\n",*p);
p++;
}
}

Another methods
#include<stdio.h>
void main ()
{
char s[11] = "Hello Kathmandu";
char *p = s;
printf("%s", p);
}

Copy of one String into another String using pointer


#include<stdio.h>
void main ()
{
char *p = "hello javatpoint";
printf("String p: %s\n", p);
char *q;
printf("copying the content of p into q...\n");
q = p;
printf("String q: %s\n", q);
}
Dynamic memory allocation in C
The concept of dynamic memory allocation in c language enables the C programmer
to allocate memory at runtime. Dynamic memory allocation in c language is possible by 4
functions of stdlib.h header file.

1. malloc()
2. calloc()
3. realloc()
4. free()

Before learning above functions, let's understand the difference between static memory
allocation and dynamic memory allocation.

1. SMA (Static Memory Allocation)


2. DMA (Dynamic Memory Allocation)

SMA : Memory created at compile time is called SMA.

DMA : Memory created at runtime is called DMA.

Let’s take quick look at the methods


malloc()
The name "malloc" stands for memory allocation.

The malloc() function reserves a single block of memory of the specified number of
bytes. And, it returns a pointer of void which can be casted into pointers of any form.
The memory created by malloc() function doesn’t have name. we can access it by its
address.
So, the pointer comes into the picture.
Syntax:
Ptr=(type_caste *) malloc(size)
Eg:
Ptr=(float*)malloc(100*sizeof(float));

The above statement allocates 400 bytes of memory. It's because the size of float is 4
bytes. And, the pointer ptr holds the address of the first byte in the allocated memory.
The expression results in a NULL pointer if the memory cannot be allocated.

Eg:-
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n, i, *ptr, sum=0;
printf("Enter number of elements: ");
scanf("%d" ,&n);
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL)
{
printf("Sorry! unable to allocate memory");
exit(0);
}
else
{
printf("Memory is allocated");
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d", ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d", sum);
free(ptr);
return 0;
}
Output
Enter number of element : 5
Memory is created
Value=10

calloc()
The name "calloc" stands for contiguous allocation.

The malloc() function allocates memory and leaves the memory uninitialized, whereas
the calloc() function allocates memory and initializes all bits to zero. it returns
a pointer of void which can be casted into pointers of any form.
Syntax:
Ptr=(type_caste *) calloc(n, size)
Where n specifies number of block and size specifies size of each block
Eg:
Ptr=(float*)malloc(25, sizeof(float));

The above statement allocates contiguous space in memory for 25 elements of


type float.

#include<stdio.h>
#include<stdlib.h>
int main()
{
int n,i,*ptr, sum=0;
printf("Enter number of elements:\n ");
scanf("%d" ,&n);
ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc
if(ptr==NULL)
{
printf("Sorry! unable to allocate memory\n");
exit(0);
}
else
{
printf("Memory allocated successfully\n");
}
printf("Enter elements of array:\n ");
for(i=0;i<n;++i)
{
scanf("%d", ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d ",sum);
free(ptr);
return 0;
}
Output
Enter number of elements : 5
Memory is allocated successfully
Enter elements of array : 10 5 2 4 8
Sum=29

free()
Dynamically allocated memory created with either calloc() or malloc() doesn't get free
on their own. You must explicitly use free() to release the space.

Syntax

free(ptr)

The above two example are shown

realloc
realloc() function is used to resize the memory block which is created by malloc() or
calloc() function.

If the dynamically allocated memory is insufficient and required more, we can change
the size of previously allocated memory using the realloc() function.

Syntax:

ptr=realloc(ptr, size)

Where ptr is a reallocated with new size

example:

#include<stdio.h>
#include<stdlib.h>
int main()
{
int *ptr, i , n1, n2;
printf("Enter size: ");
scanf("%d", &n1);

ptr = (int*) calloc(n1 , sizeof(int));

printf("Addresses of previously allocated memory:\n");


for(i = 0; i < n1; ++i)
printf("%d\n" ,ptr + i);

printf("\n Enter the new size: ");


scanf("%d", &n2);

ptr = realloc(ptr, n2 * sizeof(int));

printf("Addresses of newly allocated memory:\n");


for(i = 0; i < n2; ++i)
printf("%d\n", ptr + i);

free(ptr);

return 0;
}
Output
Enter size : 2
Address of previously allocated memory :
7301664
7301668
Enter the new size : 5
Address of newly allocated memory :
7301664
7301668
7301672
7301676
7301680

You might also like