04. Const Pointers & Generic Void Pointers in C

🟡 Difficulty: Intermediate | Read-Only Pointer Safety, Constant Addresses & Generic Memory Buffers

📖 Definition

A const pointer qualification specifies read-only immutability rules for pointer addresses or target memory values. A generic void pointer (void *) is an opaque pointer type capable of holding the memory address of any data type without an explicit cast.

🎯 Why It Is Used

  • API Read-Only Contracts: Declaring function parameters like void print_string(const char *s) guarantees to caller code that the function will not mutate the string memory.
  • Generic Memory API Abstraction: Standard library functions like malloc(), free(), memcpy(), and qsort() accept and return void* pointers to handle arbitrary types seamlessly.

⚙️ How It Works: The Clockwise-Right Rule

To read const pointer declarations correctly, read from right to left starting at the variable name:

  1. const int *p: "p is a pointer to an integer that is constant." (Value read-only via *p, address p can change).
  2. int * const p: "p is a constant pointer to an integer." (Address p fixed/immutable, value *p can change).
  3. const int * const p: "p is a constant pointer to a constant integer." (Neither address p nor value *p can change!).

📝 Syntax

// 1. Pointer to Constant Data (Value locked, Address mutable)
const int *ptr1 = &val;

// 2. Constant Pointer to Mutable Data (Address locked, Value mutable)
int * const ptr2 = &val;

// 3. Generic Void Pointer (Can point to any type)
void *generic_ptr = &val;
int retrieved_val = *(int*)generic_ptr; // MUST cast before dereferencing!

🔀 Const Pointer Qualifications Matrix

Declaration Syntax Can Modify Target Value (*p = x)? Can Modify Pointer Address (p = &y)?
int *p✅ Yes✅ Yes
const int *p (or int const *p)❌ No (Compile Error)✅ Yes
int * const p✅ Yes❌ No (Compile Error)
const int * const p❌ No (Compile Error)❌ No (Compile Error)

🌱 Beginner Example: Pointer to Const vs Const Pointer

#include <stdio.h>

int main(void) {
    int x = 10, y = 20;

    // 1. Pointer to Const (Value read-only)
    const int *ptr_to_const = &x;
    // *ptr_to_const = 15; // ERROR: Assignment of read-only location!
    ptr_to_const = &y;    // OK: Address can be changed!
    printf("ptr_to_const points to y value: %d\n", *ptr_to_const);

    // 2. Const Pointer (Address fixed)
    int * const const_ptr = &x;
    *const_ptr = 30;      // OK: Value can be mutated!
    // const_ptr = &y;    // ERROR: Assignment of read-only variable 'const_ptr'!
    printf("x mutated via const_ptr: %d\n", x);

    return 0;
}

🌼 Intermediate Example: Generic Void Pointer Swap Utility

#include <stdio.h>
#include <string.h>

// Generic memory block swapper accepting void* pointers
void generic_swap(void *a, void *b, size_t elem_size) {
    if (a == NULL || b == NULL || elem_size == 0) return;

    // Temporary stack buffer byte array
    unsigned char temp[elem_size];

    memcpy(temp, a, elem_size);
    memcpy(a, b, elem_size);
    memcpy(b, temp, elem_size);
}

int main(void) {
    int i1 = 100, i2 = 200;
    generic_swap(&i1, &i2, sizeof(int));
    printf("Swapped ints   : i1 = %d, i2 = %d\n", i1, i2);

    double d1 = 1.23, d2 = 9.87;
    generic_swap(&d1, &d2, sizeof(double));
    printf("Swapped doubles: d1 = %.2lf, d2 = %.2lf\n", d1, d2);

    return 0;
}

🌲 Advanced Example: Inspection of Opaque Generic Types

#include <stdio.h>

typedef enum { TYPE_INT, TYPE_DOUBLE, TYPE_STRING } DataType;

void print_generic_value(const void *data_ptr, DataType type) {
    if (data_ptr == NULL) return;

    switch (type) {
        case TYPE_INT:
            printf("Integer Value: %d\n", *(const int*)data_ptr);
            break;
        case TYPE_DOUBLE:
            printf("Double Value : %.2lf\n", *(const double*)data_ptr);
            break;
        case TYPE_STRING:
            printf("String Value : %s\n", (const char*)data_ptr);
            break;
    }
}

int main(void) {
    int val_int = 42;
    double val_dbl = 99.99;
    const char *val_str = "C Master Course";

    print_generic_value(&val_int, TYPE_INT);
    print_generic_value(&val_dbl, TYPE_DOUBLE);
    print_generic_value(val_str, TYPE_STRING);
    return 0;
}

🔍 Line-by-Line Explanation

  • const int *ptr_to_const: Locks target value mutation through pointer, while allowing address re-assignment.
  • void generic_swap(void *a, void *b, size_t elem_size): Accepts generic untyped addresses, performing raw byte swapping via memcpy().
  • *(const int*)data_ptr: Casts generic opaque void* to concrete const int* before dereferencing.

💻 Expected Terminal Output

ptr_to_const points to y value: 20
x mutated via const_ptr: 30
Swapped ints   : i1 = 200, i2 = 100
Swapped doubles: d1 = 9.87, d2 = 1.23
Integer Value: 42
Double Value : 99.99
String Value : C Master Course

⚠️ Common Mistakes & Pitfalls

  • Directly Dereferencing a void* Pointer: Writing *void_ptr causes compilation errors because void has no defined byte size! Always cast to a concrete pointer type (e.g. *(int*)void_ptr) first.
  • Performing Pointer Arithmetic on void*: Writing void_ptr++ is invalid under ISO C standards.

📌 Important Rules & Limitations

  • Any typed pointer implicitly converts to and from void* in C without explicit casting.
  • void* pointers CANNOT be dereferenced or incremented directly without casting to a concrete data type first.

🌐 Multilingual Explanation: English

A const int *p protects value mutation, whereas int * const p fixes pointer address re-assignment. Generic void* pointers hold arbitrary addresses but must be cast before dereferencing.

🌐 Multilingual Explanation: Hindi (Roman Script)

const int *p se pointer ke zariye value change nahi kar sakte. void* pointer kisi bhi data type ka address store kar sakta hai, lekin use dereference karne se pehle correct type cast karna zaroori hai.

🌐 Multilingual Explanation: Marathi (Roman Script)

const int *p mule value lock hote. void* pointer konthyahi type cha address hold karto, pan dereference karnyasathi cast kara lagto.

❓ Practice Questions

  1. Read from right to left: What does const char * const p mean?
  2. Why is direct dereferencing *vptr prohibited on a void *vptr pointer in ISO C?
  3. Why do functions like malloc() return a void* pointer?

🚀 Practical Coding Challenge

Write a C program named generic_array_print.c that implements a generic function void print_array(const void *arr, size_t count, size_t elem_size, void (*print_elem)(const void*)) and test it printing both an int array and a double array.

🧭 Navigation & Breadcrumbs

← Previous: 03. Double Pointers | Module 10 Guide | Next: 05. Dangling & Null Pointers →