Pointer Variables: Declaration and Initialization
You'll learn how to create variables that store memory addresses instead of regular values.
What Makes Pointer Variables Special?
In the previous lesson, you learned that every variable lives at a memory address and you can retrieve that address using the & operator. Now we take the next step: creating variables specifically designed to store those addresses.
A pointer variable holds a memory address as its value. Think of it like a sticky note that doesn't contain data directly, but instead tells you where to find that data in memory.
Declaration Syntax
To declare a pointer variable, you use the asterisk (*) symbol between the data type and the variable name:
int* ptr;
This reads as: "ptr is a pointer to an int." The asterisk tells the compiler this variable will store the address of an integer, not an integer value itself.
Initialization: Giving It an Address
An uninitialized pointer is dangerous—it points to a random memory location. You should initialize it right away, typically by assigning it the address of an existing variable:
int age = 25;
int* ptr = &age; // ptr now stores the address of age
Here, ptr contains the memory address where age lives (e.g., 0x7ffc23), not the value 25 itself.
You can also initialize a pointer to NULL (a special value meaning "points nowhere") if you don't have an address yet:
int* ptr = NULL;
Key Takeaway: Pointer variables are declared with the * syntax and store memory addresses obtained via the & operator or special values like NULL.