Chapter 25 of 44

Advanced Pointers in C (Pointer to Pointer, void, NULL & const)

So far, we've learned what a pointer is, how pointers work with arrays, and how functions can modify variables through pointers.

In this topic, we'll cover four ideas that appear again and again in real C code and in interviews:

  • Pointer to pointer (int **)

  • void pointer (void *)

  • NULL pointer

  • const with pointers

Pointer to Pointer

A pointer is also a variable, so it also has its own address. A pointer to pointer is a variable that stores the address of another pointer.

int num = 10;
int *p = #     // p stores the address of num
int **pp = &p;     // pp stores the address of p

Think of it as a chain. Suppose the addresses are 1000 for num and 2000 for p (example values only):

    pp                p                 num
┌─────────┐      ┌─────────┐      ┌─────────┐
│  2000   │ ───► │  1000   │ ───► │   10    │
└─────────┘      └─────────┘      └─────────┘
 address 3000     address 2000     address 1000

Now we can read the value in three ways:

Expression

Meaning

Value (example)

pp

Address of p

2000

*pp

Value stored in p = address of num

1000

**pp

Value stored in num

10

Each * follows one arrow in the diagram. Two stars means two jumps.

#include <stdio.h>

int main()
{
    int num = 10;
    int *p = &num;     // p stores the address of num
    int **pp = &p;     // pp stores the address of p

    printf("num   = %d\n", num);
    printf("*p    = %d\n", *p);
    printf("**pp  = %d\n", **pp);

    **pp = 50;         // changes num through two levels

    printf("num after **pp = 50 : %d\n", num);

    printf("pp points to p?   %s\n", (*pp == p) ? "yes" : "no");
    printf("p points to num?  %s\n", (p == &num) ? "yes" : "no");

    return 0;
}

Output:

num   = 10
*p    = 10
**pp  = 10
num after **pp = 50 : 50
pp points to p?   yes
p points to num?  yes

Why Do We Need a Pointer to Pointer?

In the Pointers and Functions topic, we learned that to change an int inside a function, we pass an int *.

The same rule applies one level up: to change a pointer inside a function, we pass the address of that pointer, which is an int **.

To change an int      → pass int *     (address of the int)
To change an int *    → pass int **    (address of the pointer)

Here, the function decides which variable the caller's pointer should point to:

#include <stdio.h>

void pointToLarger(int **result, int *a, int *b)
{
    if (*a > *b)
        *result = a;
    else
        *result = b;
}

int main()
{
    int x = 15, y = 42;
    int *larger = &x;

    pointToLarger(&larger, &x, &y);

    printf("Larger value = %d\n", *larger);
    printf("larger points to y? %s\n", (larger == &y) ? "yes" : "no");

    return 0;
}

Output:

Larger value = 42
larger points to y? yes

If the parameter were just int *result, the function would receive a copy of the pointer, and changing that copy would not affect larger in main().

Pointers to pointers are also used for arrays of strings (like char *argv[] in command-line arguments), dynamically allocated 2D arrays, and data structures such as linked lists.

#include <stdio.h>

int main()
{
    const char *names[] = {"Asha", "Ravi", "Meena"};
    const char **pp = names;      // points to the first element of names

    printf("%s\n", *pp);          // Asha
    printf("%s\n", *(pp + 2));    // Meena
    printf("%c\n", **(pp + 1));   // R (first char of "Ravi")

    return 0;
}

Output:

Asha
Meena
R

void Pointer (Generic Pointer)

A void pointer is a pointer that can hold the address of any type of object. It is declared using void *.

int a = 10;
float b = 2.5f;
char c = 'x';

void *ptr;

ptr = &a;   // OK
ptr = &b;   // OK
ptr = &c;   // OK

Because of this, it is also called a generic pointer.

Rules for void Pointers

  • You cannot dereference a void * directly. The compiler doesn't know what type is stored there, so it doesn't know how many bytes to read. You must first cast it to the correct pointer type:

int a = 10;
void *ptr = &a;

// printf("%d", *ptr);         // error: cannot dereference void *
printf("%d", *(int *)ptr);     // OK: cast to int *, then dereference
  • Standard C does not allow arithmetic on a void * (like ptr + 1), because the size of the pointed-to type is unknown. GCC allows it as an extension and treats the size as 1 byte, but portable code should cast to char * first.

  • In C, a void * converts automatically to and from any other object pointer type, without a cast. This is why we can write int *p = malloc(5 * sizeof(int));. malloc() returns a void *, as we will see in the Dynamic Memory Allocation topic.

Example: A Generic Print Function

#include <stdio.h>

void printValue(void *ptr, char type)
{
    if (type == 'i')
        printf("int    : %d\n", *(int *)ptr);
    else if (type == 'f')
        printf("float  : %.2f\n", *(float *)ptr);
    else if (type == 'c')
        printf("char   : %c\n", *(char *)ptr);
}

int main()
{
    int age = 21;
    float cgpa = 8.75f;
    char grade = 'A';

    printValue(&age, 'i');
    printValue(&cgpa, 'f');
    printValue(&grade, 'c');

    return 0;
}

Output:

int    : 21
float  : 8.75
char   : A

One function handles three types. The extra type argument tells it how to interpret the address. Library functions such as malloc(), memcpy() and qsort() use void * in the same way to work with any type of data.


NULL Pointer

A NULL pointer is a pointer that does not point to any valid object. It is a special value that means "this pointer points to nothing".

int *ptr = NULL;

NULL is a macro defined in <stddef.h>, and it is also available through <stdio.h>, <stdlib.h> and <string.h>.

Why Use NULL?

A local pointer that is not initialized contains a garbage address. This is called a wild pointer, and using it can silently corrupt memory or crash the program.

int *p1;          // wild pointer: points somewhere unknown
int *p2 = NULL;   // NULL pointer: clearly points to nothing

With NULL, we can check whether a pointer is safe to use:

if (ptr != NULL)
{
    printf("%d", *ptr);
}

This is the same as writing if (ptr), because a NULL pointer is treated as false in a condition.

Dereferencing a NULL pointer (*ptr when ptr is NULL) is undefined behavior. On most systems the program crashes immediately (for example, with a "segmentation fault"), which is actually helpful because the bug is easy to find.

Example: Returning "Not Found"

Functions often use NULL to signal "nothing found" or "failed". Here, a search function stores either the address of the found element or NULL:

#include <stdio.h>

int findIndex(int arr[], int n, int key, int **found)
{
    for (int i = 0; i < n; i++)
    {
        if (arr[i] == key)
        {
            *found = &arr[i];
            return i;
        }
    }

    *found = NULL;     // nothing found
    return -1;
}

int main()
{
    int marks[] = {72, 85, 90, 64};
    int *ptr = NULL;

    findIndex(marks, 4, 90, &ptr);
    if (ptr != NULL)
        printf("Found 90, value via pointer = %d\n", *ptr);

    findIndex(marks, 4, 100, &ptr);
    if (ptr == NULL)
        printf("100 not found, pointer is NULL\n");

    return 0;
}

Output:

Found 90, value via pointer = 90
100 not found, pointer is NULL

Notice that this example also uses a pointer to pointer (int **found) so that the function can set the caller's pointer.

NULL vs '\0' vs 0

Item

What it is

Used for

NULL

A null pointer constant

Pointers that point to nothing

'\0'

The null character (value 0)

Marking the end of a string

0

The integer zero

Numbers (it can also be used as a null pointer constant)

Use NULL for pointers and '\0' for characters, so the intent is clear. (The newest standard, C23, also adds the keyword nullptr for the same purpose as NULL.)


const with Pointers

In the Constants topic, we used const to stop a variable from changing. With pointers, there are two things that could be made constant:

  1. The value the pointer points to

  2. The pointer itself (the address it holds)

This gives three useful forms:

Declaration

Name

Change value (*p = ...)?

Change address (p = ...)?

const int *p (same as int const *p)

Pointer to constant

No

Yes

int *const p

Constant pointer

Yes

No

const int *const p

Constant pointer to constant

No

No

The Trick to Read Them

Look at which side of the * the word const is on:

  • const before the * → the value is protected (const int *p)

  • const after the * → the pointer is protected (int *const p)

You can also read the declaration from right to left:

const int *p        → "p is a pointer to an int that is const"
int *const p        → "p is a const pointer to an int"
const int *const p  → "p is a const pointer to an int that is const"

Always initialize a constant pointer (int *const p) when you declare it. Since it can't be assigned later, a constant pointer declared without a value would be stuck holding a garbage address (or NULL, for a global) forever.

Example

#include <stdio.h>

int sum(const int *arr, int n)
{
    int total = 0;

    for (int i = 0; i < n; i++)
    {
        total += arr[i];   // reading is allowed
        // arr[i] = 0;     // error: arr points to const int
    }

    return total;
}

int main()
{
    int a = 10, b = 20;

    const int *p1 = &a;     // pointer to const int
    p1 = &b;                // OK: the pointer itself can move
    // *p1 = 30;            // error: cannot change the value through p1

    int *const p2 = &a;     // const pointer to int
    *p2 = 30;               // OK: the value can change
    // p2 = &b;             // error: p2 cannot point elsewhere

    const int *const p3 = &b;   // const pointer to const int
    // *p3 = 40;            // error
    // p3 = &a;             // error

    printf("*p1 = %d, *p2 = %d, *p3 = %d\n", *p1, *p2, *p3);

    int marks[] = {70, 80, 90};
    printf("Sum = %d\n", sum(marks, 3));

    return 0;
}

Output:

*p1 = 20, *p2 = 30, *p3 = 20
Sum = 240

If you remove the // from any of the lines marked "error", the program will not compile.

Note that const int *p1 = &a; does not make a itself constant. It only means we can't change a through p1. We can still write a = 99; directly.

Why const Pointers Matter in Functions

Writing const in a pointer parameter is a promise: "this function will only read the data, not change it". The standard library uses this everywhere:

size_t strlen(const char *s);
char *strcpy(char *dest, const char *src);

From strcpy()'s declaration alone, you can tell that src is only read and dest is written to. It also lets you pass constant data, such as a string literal, safely.


Size of Pointers

A pointer stores an address, so its size depends on the system, not on the type it points to. On a typical 64-bit system:

#include <stdio.h>

int main()
{
    printf("sizeof(char *)   = %zu\n", sizeof(char *));
    printf("sizeof(int *)    = %zu\n", sizeof(int *));
    printf("sizeof(double *) = %zu\n", sizeof(double *));
    printf("sizeof(void *)   = %zu\n", sizeof(void *));
    printf("sizeof(int **)   = %zu\n", sizeof(int **));
    return 0;
}

Output (on a typical 64-bit system):

sizeof(char *)   = 8
sizeof(int *)    = 8
sizeof(double *) = 8
sizeof(void *)   = 8
sizeof(int **)   = 8

On a 32-bit system, these are usually 4. The C standard doesn't strictly require all pointer types to have the same size, but on common desktop systems they do.


Types of Pointers at a Glance

Pointer

Meaning

Safe to dereference?

Pointer to pointer

Stores the address of another pointer

Yes, if both levels point to valid objects

void pointer

Can hold the address of any object type

Only after casting to the correct type

NULL pointer

Points to nothing (on purpose)

No, undefined behavior

Wild pointer

Uninitialized, holds a garbage address

No, undefined behavior

Dangling pointer

Points to memory that is no longer valid (covered in Memory Management)

No, undefined behavior


Common Mistakes

  • Dereferencing a void * without casting. Write *(int *)ptr, not *ptr.

  • Casting a void * to the wrong type. If ptr holds the address of a float, reading it as *(int *)ptr gives a meaningless result (and is undefined behavior). The cast must match the real type.

  • Using a pointer without initializing it. Always initialize pointers, to a valid address or to NULL.

  • Not checking for NULL before dereferencing a pointer returned by a function.

  • Mixing up const int *p and int *const p. Check which side of * the const is on.

  • Removing const with a cast and modifying the data. If the original object was declared const, modifying it through a cast is undefined behavior. Assigning a const int * to a plain int * also makes the compiler complain, for the same reason.

  • Modifying a string literal. char *s = "hello"; s[0] = 'H'; is undefined behavior. Use const char *s = "hello"; so the compiler catches it, or use an array: char s[] = "hello";.


Interview Questions

What is the difference between const int *p and int *const p?

const int *p is a pointer to a constant int: you can't change the value through p, but p can point elsewhere. int *const p is a constant pointer: p always points to the same place, but the value there can change.

Can we dereference a void pointer?

Not directly. We must cast it to a specific pointer type first, for example *(int *)ptr.

Why does a function need an int ** parameter to change a pointer?

C passes arguments by value. To change the caller's int *, the function needs its address, which has type int **.

What is the difference between a NULL pointer and a wild pointer?

A NULL pointer is deliberately set to point to nothing and can be checked with if (ptr != NULL). A wild pointer is uninitialized and holds an unknown address that cannot be checked. Neither may be dereferenced.

What is sizeof(void *)?

It depends on the system: usually 8 bytes on 64-bit systems and 4 bytes on 32-bit systems.

Is pointer arithmetic allowed on a void *?

Not in standard C. GCC allows it as an extension (treating the size as 1), but portable code casts to char * first.

In Simple Words

A pointer to pointer stores the address of a pointer, a void pointer can point to any type, a NULL pointer points to nothing, and const can protect either the value or the pointer.

int **pp            → pointer to a pointer to int
void *vp            → generic pointer (cast before use)
int *p = NULL       → points to nothing; check before use
const int *p        → value is read-only
int *const p        → pointer is fixed
const int *const p  → both are fixed

These ideas prepare us for the next topic, Function Pointers, and for Dynamic Memory Allocation, where void * and NULL appear all the time.