Course contentsShow
← C
Lesson 134 of 1,2192. Variables and TypesFree lesson

Casting pointers (Introductory look)

Casting pointers (Introductory look)

What you'll learn: How to tell the C compiler to treat an address as a different data type than originally defined.

In previous lessons, you learned that a pointer is just a variable that holds a memory address. However, C is a "typed" language. When you declare int *p, you aren't just saying "p is an address"; you are saying "p is an address that points to an integer." The compiler uses this type to know how many bytes to read and how to interpret them.

But what if you have the right address but the wrong "label"? That is where pointer casting comes in.

The Lens Analogy

Imagine you are looking at a box through a pair of binoculars. If you use "Integer Lens," the box looks like a 4-byte whole number. if you swap to a "Character Lens," you see that same box as a single 1-byte letter. The box (the memory address) hasn't moved or changed; you are simply changing the lens you use to look at it.

Casting a pointer is like swapping that lens. You are telling the compiler, "I know you think this address points to an X, but I want you to treat it as a Y for a moment."

How to Cast

To cast a pointer, you put the desired pointer type in parentheses—(type *)—immediately before the pointer variable. This is common when dealing with generic memory or when interfacing with hardware.

#include <stdio.h>

int main() {
    int number = 65;
    
    // A standard pointer to our integer
    int *intPtr = &number;
    
    // We "cast" the int pointer into a char pointer
    // This tells C: "Look at that same address, but treat it as a character"
    char *charPtr = (char *)intPtr;
    
    printf("As integer: %d\n", *intPtr);  // Prints 65
    printf("As character: %c\n", *charPtr); // Prints 'A' (ASCII 65)

    return 0;
}

Why use it?

You won't need to cast pointers every day, but it is a superpower in C. It allows you to perform "low-level" tricks, such as inspecting the individual bytes of a large structure or working with void * (a "generic" pointer that doesn't have a type yet).

Just be careful: if you cast a pointer to a type that is larger than the original data, you might accidentally read into "forbidden" memory nearby, which can cause your program to crash.

Key takeaway

Pointer casting doesn't change the data in memory; it only changes how your program interprets the data at that specific address.