Pointer in C

What is Pointer in C ?

At its core, a pointer is a variable that stores the memory address of another variable. This enables you to indirectly access and manipulate the value of the variable it points to. Think of a pointer as a “pointer” in the real world, guiding you to a specific location in memory where your data is stored.

Declaring Pointers

To declare a pointer in C, you use an asterisk (*) before the variable name, like this:

int *ptr; // Declares a pointer to an integer

In this example, ptr is a pointer that can hold the memory address of an integer.

Initializing Pointers

Pointers should be initialized before they are used. You can initialize a pointer with the address of an existing variable:

int num = 42;
int *ptr = # // ptr now points to the memory address of num

Dereferencing Pointers

Dereferencing a pointer means accessing the value stored at the memory address it points to. This is done using the asterisk (*) operator:

int value = *ptr; // Retrieves the value stored at the memory address ptr points to

Pointer Arithmetic

C allows arithmetic operations on pointers. When you add an integer value to a pointer, it moves to the memory address of the next element of that type:

int arr[5] = {1, 2, 3, 4, 5};
int *ptr = arr;

int thirdElement = *(ptr + 2); // Accesses the third element (3) using pointer arithmetic

Passing Pointers to Functions

One of the most significant advantages of pointers is their use in passing values by reference to functions. This allows functions to modify the original data directly, rather than working with a copy:

void modifyValue(int *valPtr) {
    *valPtr = 100;

int main() {
    int num = 42;
    int *ptr = #
    modifyValue(ptr); // Changes num's value to 100

Pointers and Arrays

In C, arrays are closely related to pointers. The name of an array represents a pointer to the first element of the array:

int arr[3] = {10, 20, 30};
int *ptr = arr; // ptr points to the first element of arr

int secondElement = *(ptr + 1); // Accesses the second element (20)

Dynamic Memory Allocation

Pointers are essential when working with dynamic memory allocation using functions like malloc, calloc, and realloc:

int *dynamicArray = (int *)malloc(5 * sizeof(int)); // Allocates memory for 5 integers
dynamicArray[2] = 50; // Accessing and modifying dynamically allocated memory

free(dynamicArray); // Don't forget to free the allocated memory

Null Pointers

A pointer that doesn’t point to any valid memory location is called a null pointer. It’s a good practice to initialize pointers to NULL when declaring them:

int *ptr = NULL; // Initializing a pointer to a null pointer