PPS Pointers
PPS Pointers
POINTERS
Introduction to Pointers
Pointer Declaration and Initialization
Pointer Arithmetic and pointer Expressions
Pointers and Arrays
Pointers and Strings
Pointer to Structure
Call by Reference
Pointer to Pointer
Dynamic Memory Allocation
What is Pointer in C?
A pointer is a variable that stores the address of another variable.
This variable can be of type int, char, array, function, or any other
pointer. It is a derived data type in c.
For example, an integer variable holds (or you can say stores) an
integer value, however an integer pointer holds the address of a
integer variable.
However, in 32-bit architecture the size of a pointer is 2 byte.
Advantages:
• Pointers used to access the address of the variable.
• Pointers increase the execution speed of program.
• Pointers are an important concept in datastructures.
• Pointers are used for dynamic memory allocation.
• Pointers makes possible to return more than one value in
functions .
• Pointers make the programs simple and reduce their length.
Pointer Declarations:
Pointer declaration is similar to other type of variable except
asterisk (*) character before pointer variable name.
• Here is the syntax to declare a pointer
datatype *poitername;
Data type of a pointer must be same as the data type of the
variable to which the pointer variable is pointing.
Ex: int *ptr;
float *ptr;
char *ptr;
• ptr is the name of pointer variable (name of the memory
blocks in which address of another variable is going to be
stored).
• The data type int tells to the compiler that pointer ptr will
store memory address of integer type variable.
Initialization of C Pointer variable:
Pointer Initialization is the process of assigning address of a
variable to a pointer variable. It contains the address of a
variable of the same data type .In C language address
operator (&) is used to determine the address of a variable.
Ex: int a = 10;
int *ptr; //pointer declaration
ptr = &a; //pointer initialization
• Pointer variable always points to variables of the same
datatype.
For example:
float a;
int *ptr = &a; // ERROR, type mismatch
Accessing address and value of variable using
pointer:
We can get the value of p(pointer variable) which is the address
of a (integer variable)
C Pointer Subtraction:
• Like pointer addition, we can subtract a value from the pointer
variable. Subtracting any number from a pointer will give an address.
The formula of subtracting value from the pointer variable is given
below:
new_address= current_address- (number * size_of(data type))
Let's see the example of adding value to pointer variable
#include<stdio.h>
int main()
{
int number=50;
int *p;//pointer to int
p=&number;
printf("Address of p variable is %u \n",p);
p=p+3; //adding 3 to pointer variable
printf("After adding 3: Address of p variable is %u \n",p);
}
o/p: Address of p variable is 3214864300
After adding 3: Address of p variable is 3214864312
Let's see the example of subtracting value from the pointer
variable
#include<stdio.h>
int main()
{
int number=50;
int *p;//pointer to int
p=&number;
printf("Address of p variable is %u \n",p);
p=p-3; //subtracting 3 from pointer variable
printf("After subtracting 3: Address of p variable is %u \
n",p);
}
o/p: Address of p variable is 3214864300
After subtracting 3: Address of p variable is 3214864288
Illegal arithmetic with pointers:
• There are various operations which can not be performed
on pointers. Since, pointer stores address hence we must
ignore the operations which may lead to an illegal
address, for example, addition, and multiplication. A list of
such operations is given below.
• Address + Address = illegal
• Address * Address = illegal
• Address % Address = illegal
• Address / Address = illegal
• Address & Address = illegal
• Address ^ Address = illegal
• Address | Address = illegal
• ~Address = illegal
Pointer and Arrays in C:
When array is declared ,the compiler allocates a base address
and sufficient amount of storage to contain all the elements of
the array in contiguous memory locations
We declare an array x as follows
Ex: int arr[5] = { 1, 2, 3, 4, 5 };
Suppose the base address of arr is 1000 and each integer
requires two bytes, the five elements will be stored as follows:
Variable arr will give the base address, which is a constant
pointer pointing to arr[0]. Hence arr contains the address
of arr[0] i.e 1000.
arr has two purpose –
• It is the name of the array
• It acts as a pointer pointing towards the first element in the
array.
arr is equal to &arr[0] by default
Creating a pointer to array:
If we declare p as an integer pointer ,then we can make the
pointer p to print to the array x by the following assignment
p=x; (or) p=&x[0];
Now we can access every value of x using p++ to move from
one element to another.
The relationship between p and x is
P=&x[0]
P+1=&x[1]
p+2=&x[2]
P+3=&x[3]
P+4=&x[4]
Address of x[3]=baseaddress+(3*sizeof(int))
x[3]=1000+(3*2)=1006
*(p+3) gives the value of x[3]
(p+3) gives the address of &x[3]
Use a pointer to an array, and then use that pointer to access the
array elements. For example,
#include<stdio.h>
void main()
{
int x[5] = {1, 2, 3,4,5};
int *p ;
p=x (or) p=&x[0];
for (int i = 0; i < 5; i++)
{
printf("%d", *p);
p++;
}
} o/p:1 2 3 4 5
C - Pointers and Strings:
We know that a string is a sequence of characters which we save in
an array. And in C programming language the \0 null character
marks the end of a string.
Creating a string:
In the following example we are creating a string using
character array of size 6.
char str[6] = "Hello";
The above string can be represented in memory as follows .
Creating a pointer for the string:
The variable name of the string str holds the address of the first
element of the array i.e., it points at the starting memory
address.
So, we can create a character pointer ptr and store the address
of the string str variable in it. This way, ptr will point at the
string str.
In the following code we are assigning the address of the
string str to the pointer ptr.
char *ptr = str;
We can represent the character pointer variable ptr as follows.
Accessing string via pointer:
#include <stdio.h>
int main()
{
char str[6] = "Hello";
char *ptr = str;
while(*ptr != '\0')
{
printf("%c", *ptr); // move the ptr pointer to the next memory
location
ptr++;
}
return 0;
}
Pointer to Pointer (Double Pointer):
As we know that, a pointer is used to store the address of a
variable in C. Pointer reduces the access time of a variable.
However, In C, we can also define a pointer to store the
address of another pointer. Such pointer is known as a double
pointer (pointer to pointer). The first pointer is used to store
the address of a variable whereas the second pointer is used to
store the address of the first pointer.
How to declare a Pointer to Pointer :
The first pointer ptr1 stores the address of the variable and the
second pointer ptr2 stores the address of the first pointer.
#include <stdio.h>
int main ()
{
int var;
int *ptr;
int **pptr;
var = 3000;
ptr = &var;
pptr = &ptr;
printf("Value of var = %d\n", var );
printf("Value available at *ptr = %d\n", *ptr );
printf("Value available at **pptr = %d\n", **pptr);
return 0;
}
Pointer to Structure
A structure pointer is defined as the pointer which points to the address of the memory block that stores a structure
known as the structure pointer. Complex data structures like Linked lists, trees, graphs, etc. are created with the help of
structure pointers. The structure pointer tells the address of a structure in memory by pointing the variable to the
structure variable.
Example:
struct point {
int value;
};
int main()
{
struct point s;
return 0;
}
Pointer to Structure
Accessing the Structure Member with the Help of Pointers
There are two ways to access the members of the structure with the help of a structure pointer:
With the help of (*) asterisk or indirection operator and (.) dot operator.
With the help of ( -> ) Arrow operator.
Below is the program to access the structure members using the structure pointer with the help of the dot operator.
// C Program to demonstrate Structure pointer
#include <stdio.h>
#include <string.h>
struct Student
{
int roll_no;
char name[30];
char branch[40];
int batch;
};
int main()
{
s1.roll_no = 27;
strcpy(s1.name, "Kamlesh Joshi");
strcpy(s1.branch, "Computer Science And Engineering");
s1.batch = 2019;
return 0;
}
O/P
Pointer to Structure
Below is the program to access the structure members using the structure pointer with the
help of the Arrow operator. In this program, we have created a Structure Student containing
structure variable s. The Structure Student has roll_no, name, branch, and batch.
Output:
// C Program to demonstrate Structure pointer
#include <stdio.h>
return 0;
}
Self Referential Structure
A self-referential structure is a structure that can have members which point to a structure variable of the same type.
They can have one or more pointers pointing to the same type of structure as their member. The self-referential structure
is widely used in dynamic data structures such as trees, linked lists, and so on. The next node of a node will be pointed in
linked lists, which consists of the same struct type. It is a unique type of structure containing a member of its type. The
member of its type is a pointer variable of the same structure in which it has been declared. In the context of blockchain,
each block is linked to a previous node or a next node, similar to a linked list.
Syntax:
struct structure_name
{
datatype datatype_name;
structure_name * pointer_name;
}
E.g.:
struct node
{
int data;
struct node *next;
};
Where ‘next’ is a pointer to a struct node variable, it should be remembered that the pointer to the structure is similar to
the pointer to any other variable. Hence, a self-referential data structure is generally a structure definition that includes
at least one member that is a pointer to the structure of its kind.
The self-referential structures are beneficial in many applications that involves linked data members, such as trees and
lists. Unlike a static data structure such as an array where the size of the array limits the number of elements that can be
inserted into the array, the self- referential structure can dynamically be contracted or expanded. Operations such as
insertion or deletion of nodes in a self-referential structure involve simple alteration of the pointers present within them.
Types of self-referential structures
#include <stdio.h>
#include <conio.h>
struct ref
{
int data;
char val;
struct ref* link;
}
int main()
{
struct ref object1; //link1
object1.link = NULL;
object1.data = 10;
object1.val = 20;
struct ref object2; //
object2.link = NULL;
object2.data = 30;
object2.val = 40;
object1.link = &object2;
printf (“%d \n”, object1.link -> data);
printf (“%d \n”, object1.link -> val);
return 0;
}
Output:
30 40
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 can be defined as a
procedure in which the size of a data structure (like Array) is
changed during the runtime.
Dynamic memory allocation in c language is possible by 4
functions of stdlib.h header file.
• malloc()
• calloc()
• realloc()
• free()
These functions are defined in the <stdlib.h> header file.
1.malloc() function in C:
The name "malloc" stands for memory allocation.
The malloc() function allocates single block of requested memory.
The “malloc” or “memory allocation” method in C is used to
dynamically allocate a single large block of memory with the specified
size
It doesn’t Iniatialize memory at execution time so that it has initializes
each block with the default garbage value initially
It returns NULL if memory is not sufficient.
syntax: (type cast *) malloc(number*sizeof(datatype));
Ex: ptr= (int *) malloc( 10*sizeof(int));
The above statement allocates 40 bytes of memory. It's because the size
of int is 4 bytes. And, the pointer ptr holds the address of the first byte
in the allocated memory.
#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);
}
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;
}
2.calloc() function in C:
The name "calloc" stands for contiguous allocation.
The calloc() function allocates multiple block of requested memory.
• it is very much similar to malloc() but has two different points and
these are:
• It initializes each block with a default value ‘0’.
• It has two parameters or arguments as compare to malloc().
• It returns NULL if memory is not sufficient.
Syntax:
ptr= (type cast *) calloc(number,sizeof(int));
here, n is the no. of elements and element-size is the size of each
element.
Ex: ptr = (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in memory for 25
elements each with the size of the float.
#include<stdio.h>
#include<stdlib.h>
void main()
{
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc
if(ptr==NULL)
{
printf("Sorry! unable to allocate memory");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
}
3.realloc() function in C:
If memory is not sufficient for malloc() or calloc(), you can
reallocate the memory by realloc() function
Syntax: (type cast *)realloc(pointer name,n*sizeof(int));
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n = 4, i, *p, s = 0;
p = (int*) calloc(n, sizeof(int));
if(p == NULL)
{
printf("\nError! memory not allocated.");
exit(0);
}
printf("\nEnter elements of array : ");
for(i = 0; i < n; ++i) {
scanf("%d", p + i);
s += *(p + i);
}
printf("\nSum : %d", s);
p = (int*) realloc(p, 6);
printf("\nEnter elements of array : ");
for(i = 0; i< n; ++i) {
scanf("%d", p + i);
s += *(p + i); }
printf("\nSum : %d", s); } In the above program, The memory block is allocated by calloc() and sum of
elements is calculated. After that, realloc() is resizing the memory block from 4 to 6 and calculating their
sum.
free() function:
The function free() is used to de-allocate the memory
allocated by the functions malloc ( ), calloc ( ),
free() Syntax:
free (pointer name);