Implicit vs explicit pointer types
What you'll learn: How the specific data type of a pointer tells the computer how to interpret the memory it points to.
The Memory Address is Just a Number
At its simplest level, every memory address is just a number—a coordinate in your RAM. If you tell a friend to go to "123 Maple Street," that is an implicit piece of information. They know the address, but they don't know if they are looking for a massive apartment complex or a tiny garden shed.
In C, the void * (void pointer) is the ultimate implicit type. It holds an address, but it has no idea what is stored there. It’s just a raw location.
The Explicit Type is the Instruction Manual
When we declare a pointer like int *myPtr or char *myPtr, we are being explicit. We aren't just giving C the address; we are giving it the "instruction manual" for how to read that memory.
- An
int *tells C: "Start at this address and read the next 4 bytes as a whole number." - A
char *tells C: "Start at this address and read only 1 byte as a character."
The address might be exactly the same, but the explicit type changes how the dereference operator (*) behaves.
Seeing the Difference in Code
Even if two pointers point to the exact same spot in memory, their type dictates what they "see."
#include <stdio.h>
int main() {
int number = 1025; // In memory, this takes 4 bytes
// Explicit int pointer: Sees the whole integer
int *intPtr = &number;
// Explicit char pointer: Points to the same spot, but only sees 1 byte
char *charPtr = (char *)&number;
printf("As an int: %d\n", *intPtr); // Outputs 1025
printf("As a char: %d\n", *charPtr); // Outputs 1 (the first byte of 1025)
return 0;
}
In the example above, intPtr and charPtr hold the same memory address. However, because charPtr is explicitly typed as a char, it only looks at a tiny slice of the data.
Why This Matters
If pointers didn't have explicit types, the compiler wouldn't know how much memory to retrieve or how to mathematically manipulate the data. By giving a pointer a type, you are defining the "window" through which you view the raw bytes of your computer.
Key takeaway
An address tells you where data starts, but the pointer's explicit type tells C how many bytes to read and how to interpret them.