Pointers in C Programming Language

A pointer in C programming language is a variable which is used to store the address of another variable. It is one of the most powerful features of the C programming language. Pointers are used everywhere in the C language. Once you master the use of pointers, you will use them everywhere to make the code more efficient and faster.

Some operations in C, can be performed efficiently using pointers like dynamic memory allocation, dynamic data structures like linked list and trees, pass arguments to a function as Call by Reference, access array elements etc.
To become an expert C programmer, it is necessary to have deep understanding of pointers.


What Are Pointers

A variable in C is the name given to a memory location, where a program can store data. A program can store and manipulate the value stored using variable's identifier. When we declare a variable in C, compiler reserve space in memory to hold the value assigned to this variable.

We can access the value of this variable either by variable identifier or by directly accessing the memory location using pointers. Every memory location is given a unique address, once you know the address of a memory location(variable), you'll then be able to go to that address and retrieve the data stored in it. To get the address of any variable, we can use &(Address of) operator and to retrieve the value stored at a memory location we can use *(Value of Operator).


Advantages of Pointers

  • We can dynamically allocate or deallocate space in memory at run time by using pointers.

  • Using pointers we can return multiple values from a function.

  • We can pass arrays to a function as call by Reference.

  • Pointers are used to efficiently access array elements, as array elements are stored in adjacent memory locations. If we have a pointer pointing to a particular element of array, then we can get the address of next element by simply incrementing the pointer.

  • Pointers in C are used to efficiently implement dynamic Data Structures like Queues, Stacks, Linked Lists, Tress etc.

  • The use of pointers results into faster execution of program.

Pointer Operators

While handling a data through pointers, we need to know the address of a variable and second is given a memory address or pointer we want to access data stored at that location. Address of(&) and Value of(*) operators are used to perform above mentioned pointer operations respectively.


Address of Operator(&)

The & is a unary operator in C which returns the memory address of the passed operand. This is also known as address of operator. A pointer contains the memory address of some object.


Value of Operator(*)

The * is a unary operator which returns the value of object pointer by a pointer variable. It is known as value of operator. It is also used for declaring pointer variable.
For Example

    int A = 100;
    int *ptr = &A;

In the first statement, we first declare an integer variable and initialize it with value 100. In second statement, we are declaring a pointer to a variable of type int and initializing it with address of A.


Pointer Declaration

A pointer is a derived data type that is created from fundamental data types. We use (*) for defining pointer variables. Here is the syntax of declaring a pointer variable.

<data_type> *<identifier>;
For Example
    int *ptr;

Above pointer declaration specifies that, ptr is a pointer variable that will store the memory address where an integer value is stored.
We can also initialize a pointer as follows:

    int count = 10;
    int *ptr = &count;

Integer variable 'count' is the name to a memory location where value 10 is stored. Let the memory address of count is "52436721". Then pointer variable ptr will contain address of count variable that is "52436721"

#include <stdio.h>

int main () {
   int  count = 10;
   int *ptr = &count;

   printf("Value of count variable is %d\n", count);
   printf("Address of count variable: %x\n", ptr);
   printf("Value retrieved through pointer : %d\n", *ptr);

   return 0;
}
Output
Value of count variable is 10
Address of count variable: 22fe44 
Value retrieved through pointer : 10

NULL Pointers in C

NULL pointer in C is a pointer which is pointing to nothing. It is used to initialize a pointer at the time of declaration if we don't have any explicit value to initialize. It is a good practice to initialize a pointer with NULL to ensure that it is not pointer to a random memory location. The NULL is a macro constant with a value of zero defined in various C header files like stdio.h, stdlib.h, alloc.h etc.

#define NULL 0
A pointer initialized with NULL is known as NULL pointer.
int *ptr = NULL;

Pointer ptr is initialized with NULL. Pointer ptr is not pointing to any valid memory location. We can check whether a pointer is a NULL pointer or not as follows:

if(ptr == NULL)
if(!ptr) 
#include <stdio.h>

int main(){
   int *ptr = NULL;
   printf("The value of ptr is %x\n", ptr);
   
   if(ptr == NULL){
        printf("ptr is NULL Pointer\n");
   }
   
   if(!ptr){
        printf("ptr is NULL Pointer\n");
   }
   return 0;
}
Output
The value of ptr is 0
ptr is NULL Pointer
ptr is NULL Pointer

Size Of Pointer Variable

Size of a pointer variable is system dependent. A memory address is considered as integer value. Size of a pointer is fixed, it doesn't depend on the data type it is pointing to. We can use size of operator to get the size of a pointer.

#include<stdio.h>

int main() {
    int count = 10;
    float sum = 20.5;
    int *null_ptr = NULL;
    int *int_ptr = &count;
    float *float_ptr = &sum;
    
    printf("Size of NULL Pointer : %d Bytes\n", 
        sizeof(null_ptr)); 
    printf("Size of Integer Variable : %d Bytes\n", 
        sizeof(count));
    printf("Size of Integer Pointer : %d Bytes\n", 
        sizeof(int_ptr));
    printf("Size of Float Variable : %d Bytes\n", 
        sizeof(sum));
    printf("Size of Float Pointer : %d Bytes\n", 
        sizeof(float_ptr));

    return 0;
}
Output
Size of NULL Pointer : 8
Size of Integer Variable : 4
Size of Integer Pointer : 8
Size of Float Variable : 4
Size of Float Pointer : 8

Pointer to a Pointer in C

A pointer to a pointer in C programming is a pointer variable which is used to store the address of another variable. A pointer can store the address of another pointer variable also like any other data type pointer.

A pointer to a pointer means, first pointer will contains the address of second pointer and second pointer can will contain the add of actual value stored in memory.
We use double * operator to define a pointer to a pointer.

<data_type> **<identifier>;
For Example
int count = 10;
int *ptr = &count; /* Pointer to an integer variable */
int **ptrToPtr = &ptr; /* Pointer to a pointer */ 

To access the value of count variable using pointer variable 'ptr', we need one asterisk operator(*) like

*ptr;

and to access the value of count variable using pointer to a pointer variable 'ptrToPtr', we need two asterisk operator(*) like

**ptrToPtr;

first asterisk returns the memory address stored inside pointer 'ptr' and second asterisk retrieves the value stored at memory location pointer by 'ptr'.


C program to show the use of pointer to a pointer

#include <stdio.h>

int main () {
   int count = 10;
   /* pointer to an integer variable */
   int *ptr = &count;
   /* pointer to a pointer*/
   int **ptrToPtr = &ptr;
   
   printf("Value of count variable = %d\n", count);
   printf("Value of count variable retreived uisng ptr %d\n", *ptr);
   printf("Value of count variable retreived uisng ptrToPtr = %d\n", **ptrToPtr);

   return 0;
}
Output
Value of count variable = 10
Value of count variable retreived uisng ptr 10
Value of count variable retreived uisng ptrToPtr = 10

Passing Pointer to Function in C

In C programming, we can pass the address of the variable to the formal arguments of a function. This method of calling a function by passing pointer arguments is known as call by reference. Any change in the value of formal parameters inside function will effect the value of actual argument. To pass a pointer to a function, we have to declare the function argument of pointer type.


C program to show how to pass pointer to a function

#include <stdio.h>
  
void getDoubleValue(int *F){
   *F = *F + 2;
   printf("F(Formal Parameter) = %d\n", *F);
}
 
int main(){
   int A;
   printf("Enter a numbers\n");
   scanf("%d", &A);
   /* Calling function using call by reference */
   getDoubleValue(&A);
   /* Any change in the value of formal parameter(F)
   will effect the value of actual parameter(A) */
   printf("A(Actual Parameter) = %d\n", A);
    
   return 0;
}
Output
Enter a numbers
7
F(Formal Parameter) = 9
A(Actual Parameter) = 9

Passing an Array to a Function Using Pointers

We can pass a one dimensional array to a function by passing the base address(address of first element of an array) of the array. We can either pas the name of the array(which is equivalent to base address) or pass the address of first element of array like &array[0]. Similarly, we can pass multi dimensional array also as formal parameters.

Different ways of declaring function which takes an array as input
Function argument as a pointer to the data type of array.
int testFunction(int *array){
  /* Function body */
} 
By specifying size of an array in function parameters.
int testFunction(int array[10]){
/* Function body */
}
By passing unsized array in function parameters.
int testFunction(int array[]){
/* Function body */
}

C Program to show different ways of passing pointer to a function

#include <stdio.h>
 
/* This function takes integer pointer as input */
void printArraySumOne(int *array, int size){
    int i, sum = 0;
    for(i=0; i<size; i++){
     sum += array[i];
    }
    printf("1. Array sum : %d\n", sum);
}
 
/* This function takes sized array as input */
void printArraySumTwo(int array[5], int size){
    int i, sum = 0;
    for(i=0; i<size; i++){
     sum += array[i];
    }
    printf("2. Array sum : %d\n", sum);
}
 
/* This function takes unsized array as input */
void printArraySumThree(int array[], int size){
    int i, sum = 0;
    for(i=0; i<size; i++){
     sum += array[i];
    }
    printf("3. Array sum : %d\n", sum);
}
 
int main(){
   int array[5]={1, 2, 3, 4, 5};
   
   printArraySumOne(array, 5);
   printArraySumTwo(array, 5);
   printArraySumThree(array, 5);
    
   return 0;
} 
Output
1. Array sum : 15
2. Array sum : 15
3. Array sum : 15

Returning Pointer from Function in C

In C programming, we can return a pointer from a function like any other data type.

Points to Remember
We should not return pointer to a local variable declared inside a function because as soon as control returns from a function all local variables gets destroyed. If we want to return pointer to a local variable then we should declare it as a static variable so that it retains it's value after control returns from function.

Declaration of a Function Returning Pointer

int* getEvenNumbers(int N){
/* Function Body */
}

C Program Returning a Pointer from a Function

#include <stdio.h>
 
/* This function returns an array of N even numbers */
int* getOddNumbers(int N){
    /* Declaration of a static local integer array */
    static int oddNumberArray[100];
    int i, even = 1;
     
    for(i=0; i<N; i++){
        oddNumberArray[i] = even;
        even += 2;
    }
    /* Returning base address of oddNumberArray array*/
    return oddNumberArray;
}
 
int main(){
   int *array, counter;
   array = getOddNumbers(10);
   printf("Odd Numbers\n");
   
   for(counter=0; counter<10; counter++){
       printf("%d\n", array[counter]);
   }
    
   return 0;
} 
Output
Odd Numbers
1
3
5
7
9
11
13
15
17
19