C Pointers

C pointers are powerful programming tools that allow you to manipulate memory addresses in your programs. While they may seem intimidating at first, understanding pointers is essential to becoming a proficient C programmer. In this article, we will cover the basics of C pointers and how to use them in your programs.

What is a pointer?

A pointer is a variable that stores the memory address of another variable. In other words, a pointer “points” to the location in memory where another variable is stored. Pointers are declared using the asterisk (*) symbol, and the memory address is obtained using the ampersand (&) symbol. For example:

int x = 5;
int *p = &x;

In this example, we declare an integer variable x with a value of 5. We then declare a pointer variable p of type int* (an integer pointer) and assign it the memory address of x using the & operator. The variable p now “points” to the memory location where x is stored.

Dereferencing a pointer

Once we have a pointer, we can access the value of the variable it points to using the asterisk (*) operator. This is known as “dereferencing” the pointer. For example:

int x = 5;
int *p = &x;
printf("%d", *p); // prints 5

In this example, we use the * operator to dereference the pointer p and print the value of the variable it points to, which is 5.

Pointer arithmetic

Pointers can also be used to perform arithmetic operations on memory addresses. For example, adding an integer to a pointer will advance it to the next memory location. Subtracting an integer from a pointer will move it backwards in memory. For example:

int x[3] = {1, 2, 3};
int *p = x;
printf("%d", *(p + 1)); // prints 2

In this example, we declare an array of integers x with three elements. We then declare a pointer p and assign it the memory address of the first element of x. We can use pointer arithmetic to access the second element of x by adding 1 to the pointer p and dereferencing it with the * operator.

Pointer to pointer

Pointers can also be used to create pointers to other pointers. This is known as a “pointer to pointer” or “double pointer”. For example:

int x = 5;
int *p = &x;
int **pp = &p;

In this example, we declare a pointer p that points to an integer variable x. We can then declare another pointer pp that points to p. The variable pp is a pointer to a pointer, or a double pointer.

Using pointers with functions

Pointers are often used with functions to pass values by reference. This allows the function to modify the original variable passed to it, rather than working with a copy. For example:

void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

int main() {
    int x = 5;
    int y = 10;
    swap(&x, &y);
    printf("%d %d", x, y); // prints 10 5
}

In this example, we declare a function swap that takes two integer

About the Author: Pankaj Bisht