fbpx

Exploring Types of Pointers in C Programming

Exploring Types of Pointers in C Programming


INTRODUCTION

In C programming, pointers are a core concept that allow for powerful memory manipulation. A pointer is a variable that stores the memory address of another variable, function, or even another pointer, making it a key tool for efficient, low-level access to memory.

Uses of Pointers
Pointers are fundamental for several operations in C, such as:

  • Dynamic Memory Allocation: Pointers enable memory allocation during runtime instead of compile time, which is helpful in managing data structures with unpredictable sizes.
  • Low-Level Memory Access: With pointers, you can directly manipulate values stored at specific memory addresses, enhancing control and efficiency.

Pointers

  • Pointers is one core concepts present in the C programming language
  • Pointer is used to store the memory addresses of variable,functions and pointers

Uses of pointers

  • Dynamic memory allocation
  • Low Level access memory:
  • Dynamic memory allocation: Allocating the memory at runtime means instead of allocating the memory at compile time we  can allocate the memory at runtime.

For example  if we  want to allocate the memory for an array at runtime  getting the size of the array

#include<stdio.h>

int main()

{

int n;

printf(“Enter the no of elements”);

scanf(“%d”,&n);

 int *arr=(int *) malloc(n*sizeof(int ));  // allocating  the memory at runtime.

for(int i=0;i<n;i++)

{

scanf(“%d”,&arr[i]);

}

for(int j=0;j<n;j++)

{

Printf(“%d”,arr[i]);

}

}

}

Low level memory access:

    By using the the address we can edit the value present at particular address.

What is pointers in c:

Pointers is a variable that holds the memory address of the another variable, it is a derived datatype.

The size of pointers in c only depends on system architecture.:

32-bit Systems: On a 32-bit system, pointers are typically 4 bytes (32 bits) in size. This allows them to address up to 2^{32} memory locations, which equals 4 GB of addressable memory space.

 64-bit Systems: On a 64-bit system, pointers are usually 8 bytes (64 bits) in size. This allows addressing up to2^{64}memory locations,

int *int_ptr;     // Pointer to int

float *float_ptr; // Pointer to float

char *char_ptr;   // Pointer to char

printf(“Size of int pointer: %zu bytes\n”, sizeof(int_ptr));

printf(“Size of float pointer: %zu bytes\n”, sizeof(float_ptr));

printf(“Size of char pointer: %zu bytes\n”, sizeof(char_ptr));

From the above example size of the pointer depends on system architecture not an type of data.

Syntax of c Pointers:

datatype *p:

datatype:datatype of  pointer;

p:name of the pointer;

*:Dereferencing operator;

How to use pointer:

The use of pointers in C can be divided into three steps:

  1. Pointer Declaration
  2. Pointer Initialization
  3. Pointer Dereferencing

1. Pointer Declaration

In pointer declaration, we only declare the pointer but do not initialize it.

 To declare a pointer, we use the ( * ) dereference operator before its name.   

Example

int *ptr;

The pointer declared here will point to some random memory address as it is not initialized. Such pointers are called wild pointers.

2. Pointer Initialization

Pointer initialization is the process where we assign some initial value to the pointer variable.

We generally use the ( &: ampersand ) addressof operator to get the memory address of a variable and then store it in the pointer variable.

Example

int var = 10;
int * ptr;
ptr = &var;

We can also declare and initialize the pointer in a single step.

 This method is called pointer definition as the pointer is declared and initialized at the same time.

Example

int *ptr = &var;

3. Pointer Dereferencing

Dereferencing a pointer is the process of accessing the value stored in the memory address specified in the pointer.

We use the same ( * ) dereferencing operator that we used in the pointer declaration.

Example : // C program to illustrate Pointers

#include <stdio.h>

void function()

{

    int var = 10;

    // declare pointer variable

    int* ptr;

    // note that data type of ptr and var must be same

    ptr = &var;

    // assign the address of a variable to a pointer

    printf(“Value at ptr = %p \n”, ptr);

    printf(“Value at var = %d \n”, var);

    printf(“Value at *ptr = %d \n”, *ptr);

}

// Driver program

int main()

{

    function();

return 0;

}

Types of pointers:

Types of pointers id defined based on type of pointers   in which it is defined  based on the type of data the pointer is pointing to

  • Integer Pointer
  • char pointer
  • Array Pointer
  • Function Pointer
  • Void Pointer.
  • Structure pointer
  • Null Pointer
  • Double Pointer

  • Integer Pointer

Integer Pointer is called as pointer to integers

Syntax :

Eg: int *p;

  Int x=10;

p=&x;

  • char pointer

Character pointer is a pointer pointing to character;

Char z=’a’;

Eg:  char *p;

 p=&z

  • Array Pointer:

Syntax:

data_type (*var_name)[size_of_array];

Here:

  • data_typeis the type of data that the array holds.
  • var_nameis the name of the pointer variable.
  • size_of_arrayis the size of the array to which the pointer will point.

Example

int (*ptr)[10];

It is pointer pointing to an array.

#include<stdio.h>

              int main()

{

  int arr[5] = { 1,3,4,6,5 };

  int *ptr = arr; // pointer to an integer

 int (*p)[5]; // pointer to array of integer.

ptr=arr

p=&arr

 

  printf(“%p\n”, ptr);

  return 0;

}

1. Pointers and Two-Dimensional Arrays

In the above program, we have a pointer ptr that points to the 0th element of the array.

If we want to point the whole array Then we can declare a pointer like this

// C program to understand difference between

// pointer to an integer and pointer to an

// array of integers.

#include<stdio.h>

int main()

{

                       

    int *p;   // Pointer to an integer

    int (*ptr)[5];     // Pointer to an array of 5 integers

    int arr[5]; 

    p = arr; // Points to 0th element of the arr.

    ptr = &arr; // Points to the whole array arr.

 

    printf(“p = %p, ptr = %p\n”, p, ptr);

   

    p++;

    ptr++;

   

    printf(“p = %p, ptr = %p\n”, p, ptr);

   

    return 0;

}

Pointer to Multidimensional Array:

1. Pointers and Two-Dimensional Arrays

In a two-dimensional array,

-we can access each element by using two subscripts,

-where the first subscript represents the row number and the second subscript represents the column number.

The elements of 2-D array can be accessed with the help of pointer notation also.

 Suppose arr is a 2-D array, we can access any element arr[i][j] of the array using the pointer expression *(*(arr + i) + j). Now we’ll see how this expression can be derived. 
Let us take a two dimensional array arr[3][4]

int arr[3][4] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} }; 

 

// C program to print the elements of 3-D

// array using pointer notation

#include<stdio.h>

int main()

{

  int arr[2][4][2] = {

                       {

                         {5, 10},

                         {6, 11},

                         {7, 12},

                         {8,13}

                       },

                       {

                         {20, 30},

                         {21, 31},

                         {22, 32},

                         {23,33}

                       }

                     };

  int i, j, k;

  for (i = 0; i < 2; i++)

  {

    for (j = 0; j < 4; j++)

    {

       for (k = 0; k < 2; k++)

         printf(“%d\t”, *(*(*(arr + i) + j) +k));

       printf(“\n”);

    }

  }

  return 0;

}

Function Pointer

  • A function pointer in C and C++ is a pointer that points to a function instead of a data value.
  • This allows you to store the address of a function and call it indirectly through the pointer.
  • Function pointers are useful for implementing callbacks, handling events, or creating more flexible and reusable code.

Ex:1:

#include <stdio.h>

// Function that takes two integers and returns their sum

int add(int a, int b) {

    return a + b;

}

int main() {

    // Declare a function pointer

    int (*func_ptr)(int, int);

    // Assign the address of the add function to the pointer

    func_ptr = &add;

    // Call the function using the pointer

    int result = func_ptr(5, 3); // This calls add(5, 3)

    // Print the result

    printf(“Result of addition: %d\n”, result); // Outputs: Result of addition: 8

    return 0;

}

Ex:2

#include <stdio.h>

// Function that takes two integers and returns their sum

int add(int a, int b) {

    return a + b;

}

// Function that takes two integers and returns their product

int multiply(int a, int b) {

    return a * b;

}

int main() {

    // Declaring function pointers

    int (*operation)(int, int);

    // Assigning the add function to the pointer

    operation = &add;

    printf(“Addition: %d\n”, operation(5, 3)); // Outputs: Addition: 8

    // Assigning the multiply function to the pointer

    operation = &multiply;

    printf(“Multiplication: %d\n”, operation(5, 3)); // Outputs: Multiplication: 15

    return 0;

}

Void Pointer

  • A void pointer (also known as a generic pointer) in C and C++ is a special type of pointer that can point to any data type.
  • It is declared using the void keyword and does not have a specific data type associated with it.
  • This makes void pointers versatile, but you cannot dereference them directly without first casting them to a specific pointer type.

Ex:

#include <stdio.h>

int main() {

    int num = 42;          // An integer variable

    float fnum = 3.14;    // A float variable

    // Declare a void pointer

    void *ptr;

    // Point the void pointer to an integer

    ptr = &num;

    // Cast and dereference the void pointer to access the integer value

    printf(“Value of num: %d\n”, *(int *)ptr); // Outputs: Value of num: 42

    // Point the void pointer to a float

    ptr = &fnum;

    // Cast and dereference the void pointer to access the float value

    printf(“Value of fnum: %.2f\n”, *(float *)ptr); // Outputs: Value of fnum: 3.14

    return 0;

}

Structure Pointer

A structure pointer is a pointer that points to a structure variable. It allows you to access the members of a structure using the pointer.

#include <stdio.h>

// Define a structure

struct Person {

    char name[50];

    int age;

};

int main() {

    // Declare and initialize a structure variable

    struct Person person = {“Alice”, 30};

    // Declare a pointer to the structure

    struct Person *ptr;

    // Point the pointer to the structure variable

    ptr = &person;

    // Access structure members using the pointer

    printf(“Name: %s\n”, ptr->name); // Outputs: Name: Alice

    printf(“Age: %d\n”, ptr->age);   // Outputs: Age: 30

    return 0;

}

Null Pointer

  • A null pointer is a pointer that does not point to any valid memory location. It is typically used to indicate that the pointer is not initialized or that it is not currently pointing to any object.

#include <stdio.h>

int main() {

    // Declare a null pointer

    int *ptr = NULL;

    // Check if the pointer is null

    if (ptr == NULL) {

        printf(“Pointer is null.\n”); // Outputs: Pointer is null.

    } else {

        printf(“Pointer is not null.\n”);

    }

    return 0;

}

3. Double Pointer

  • A double pointer (or pointer to a pointer) is a pointer that points to another pointer.
  • It is used when you need to modify the pointer itself or when dealing with multi-dimensional arrays and dynamic memory allocation.

#include <stdio.h>

#include <stdlib.h>

int main() {

    // Declare a double pointer

    int **ptr;

    // Allocate memory for a pointer to int

    ptr = (int **)malloc(sizeof(int *)); // Allocate memory for a single pointer

    // Allocate memory for an int

    *ptr = (int *)malloc(sizeof(int)); // Allocate memory for an int

    // Assign a value

    **ptr = 42; // Assigning value 42 to the integer

    // Access the value using the double pointer

    printf(“Value: %d\n”, **ptr); // Outputs: Value: 42

    // Free allocated memory

    free(*ptr); // Free the memory for the int

    free(ptr);  // Free the memory for the pointer to int

    return 0;

}