Home C Pointers in C tutorial

Pointers in C tutorial

Pointers in C are variables that store the memory addresses of other variables.

They are powerful tools that allow you to directly manipulate memory, work with arrays and functions, and manage dynamic memory allocation.

Understanding pointers is essential for mastering C programming.

1. Basic Syntax of Pointers

data_type *pointer_name;
  • data_type: The type of data the pointer will point to.
  • *: Indicates that this variable is a pointer.
  • pointer_name: The name of the pointer variable.

2. Declaring and Initializing Pointers

A pointer is declared using the * symbol, and it stores the address of another variable.

#include <stdio.h>

int main() {
    int num = 10;
    int *ptr = # // Pointer ptr stores the address of num

    printf("Address of num: %p\n", (void*)&num);
    printf("Value of ptr: %p\n", (void*)ptr);
    printf("Value pointed to by ptr: %d\n", *ptr); // Dereferencing

    return 0;
}

Explanation:

  • &num gives the address of num, which is stored in ptr.
  • *ptr is the dereferenced value, which retrieves the data at the address held by ptr.

Output:

Address of num: 0x... (address of num)
Value of ptr: 0x... (same as address of num)
Value pointed to by ptr: 10

3. Pointer Dereferencing

Dereferencing a pointer means accessing the value stored at the address the pointer holds.

#include <stdio.h>

int main() {
    int value = 50;
    int *ptr = &value;

    printf("Value of value: %d\n", value);
    printf("Value through ptr: %d\n", *ptr);

    *ptr = 100; // Changing value through pointer
    printf("New value of value: %d\n", value);

    return 0;
}

Explanation:

  • *ptr = 100 changes the value stored at ptr’s address, modifying value.

Output:

Value of value: 50
Value through ptr: 50
New value of value: 100

4. Null Pointers

A null pointer is a pointer that doesn’t point to any valid memory address. It’s typically used to indicate that the pointer is not currently assigned.

#include <stdio.h>

int main() {
    int *ptr = NULL; // Null pointer
    if (ptr == NULL) {
        printf("Pointer is null\n");
    } else {
        printf("Pointer is not null\n");
    }

    return 0;
}

Explanation:

  • NULL is used to initialize a pointer that does not point to a valid memory location.

Output:

Pointer is null

5. Pointers and Arrays

In C, an array name itself acts as a pointer to the first element of the array. You can use pointers to iterate over an array.

#include <stdio.h>

int main() {
    int arr[] = {10, 20, 30, 40};
    int *ptr = arr; // Points to arr[0]

    for (int i = 0; i < 4; i++) {
        printf("Element %d: %d\n", i, *(ptr + i)); // Accessing array elements with pointer
    }

    return 0;
}

Explanation:

  • ptr + i moves ptr to each element of the array.
  • *(ptr + i) dereferences the pointer to access each element.

Output:

Element 0: 10
Element 1: 20
Element 2: 30
Element 3: 40

6. Pointer Arithmetic

You can increment and decrement pointers, which will move the pointer by the size of the data type it points to.

#include <stdio.h>

int main() {
    int arr[] = {10, 20, 30, 40};
    int *ptr = arr;

    printf("Initial value: %d\n", *ptr); // arr[0]
    ptr++; // Move to next element
    printf("Next value: %d\n", *ptr); // arr[1]

    return 0;
}

Explanation:

  • ptr++ increments ptr to point to the next element of the array.

Output:

Initial value: 10
Next value: 20

7. Pointers to Pointers

A pointer to a pointer is a pointer that stores the address of another pointer. This is often used in dynamic memory management and complex data structures.

#include <stdio.h>

int main() {
    int value = 10;
    int *ptr = &value;    // Pointer to int
    int **pptr = &ptr;    // Pointer to pointer to int

    printf("Value: %d\n", value);
    printf("Value through ptr: %d\n", *ptr);
    printf("Value through pptr: %d\n", **pptr);

    return 0;
}

Explanation:

  • *ptr gives the value of value.
  • **pptr gives the value of value by dereferencing pptr twice.

Output:

Value: 10
Value through ptr: 10
Value through pptr: 10

8. Function Pointers

Function pointers store the address of a function and allow calling functions indirectly, which is useful for callback functions.

#include <stdio.h>

void greet() {
    printf("Hello, World!\n");
}

int main() {
    void (*func_ptr)() = greet; // Function pointer to greet
    func_ptr(); // Calling the function using the pointer

    return 0;
}

Explanation:

  • func_ptr is a pointer to greet.
  • func_ptr() calls greet indirectly.

Output:

Hello, World!

9. Pointers with Dynamic Memory Allocation

Pointers are essential for managing dynamically allocated memory with functions like malloc and free.

#include <stdio.h>
#include <stdlib.h>

int main() {
    int *ptr = (int*)malloc(sizeof(int) * 3); // Allocate memory for 3 integers

    if (ptr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }

    // Initialize and print elements
    for (int i = 0; i < 3; i++) {
        ptr[i] = i * 10;
        printf("Element %d: %d\n", i, ptr[i]);
    }

    free(ptr); // Free allocated memory
    return 0;
}

Explanation:

  • malloc allocates memory for 3 integers, and ptr stores the address of the allocated memory.
  • free(ptr) releases the allocated memory when it’s no longer needed.

Output:

Element 0: 0
Element 1: 10
Element 2: 20

10. Passing Pointers to Functions

Passing a pointer to a function allows the function to modify the original variable's value.

#include <stdio.h>

void doubleValue(int *n) {
    *n *= 2; // Modify the value at the pointer's address
}

int main() {
    int num = 10;
    printf("Original value: %d\n", num);

    doubleValue(&num); // Pass the address of num
    printf("Doubled value: %d\n", num);

    return 0;
}

Explanation:

  • doubleValue receives a pointer to num and doubles the value of num through the pointer.

Output:

Original value: 10
Doubled value: 20

Summary Table of Pointer Operations

Pointer Concept Description Example Code
Declaring and initializing Declares a pointer and assigns it an address int *ptr = #
Dereferencing Accesses the value at the pointer's address *ptr = 20;
Null pointer A pointer that points to no valid memory location int *ptr = NULL;
Array and pointer equivalence Uses pointers to iterate over an array int *ptr = arr; *ptr, *(ptr + i);
Pointer arithmetic Increments and decrements pointers ptr++
Pointer to pointer Pointer that stores the address of another pointer int **pptr = &ptr;
Function pointer Stores the address of a function void (*func_ptr)() = func;
Dynamic memory allocation Allocates and deallocates memory malloc, free
Passing pointer to function Allows a function to modify the original variable void func(int *ptr) { *ptr = 5; }

Complete Example: Using Pointers for Array Manipulation

This example demonstrates various pointer concepts to manipulate an array, calculate the sum, and find the average.

#include <stdio.h>
#include <stdlib.h

>

void calculateSumAndAverage(int *arr, int size, int *sum, float *average) {
    *sum = 0;
    for (int i = 0; i < size; i++) {
        *sum += arr[i];
    }
    *average = (float)(*sum) / size;
}

int main() {
    int size;
    printf("Enter the number of elements: ");
    scanf("%d", &size);

    int *arr = (int*)malloc(size * sizeof(int));
    if (arr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }

    printf("Enter %d elements:\n", size);
    for (int i = 0; i < size; i++) {
        scanf("%d", &arr[i]);
    }

    int sum;
    float average;
    calculateSumAndAverage(arr, size, &sum, &average);

    printf("Sum: %d, Average: %.2f\n", sum, average);

    free(arr);
    return 0;
}

Explanation:

  • calculateSumAndAverage takes an array pointer and calculates the sum and average.
  • malloc allocates memory for the array, which is later freed with free(arr).

Sample Output:

Enter the number of elements: 3
Enter 3 elements:
10
20
30
Sum: 60, Average: 20.00

Pointers in C are essential for efficient memory management and low-level data manipulation.

You may also like