The difference between int *p and *p
What you'll learn: How to distinguish between creating a pointer and using it to access data.
When you first see the asterisk (*) in C, it’s confusing because it changes its meaning based on where it sits. It’s like the difference between a label on a moving box and the act of opening that box.
int *p — The Labeling (Declaration)
When you see the asterisk paired with a data type (like int, char, or float), you are declaring a pointer. You are telling the computer: "I am creating a variable named p, but it won't hold a normal number. It will hold the memory address of an integer."
Think of this as creating a specialized business card. The card isn't the person; it just tells you where their office is located.
int age = 25; // A normal variable
int *p; // DECLARATION: p is a pointer to an int
p = &age; // p now stores the address of age
*p — The Opening (Dereferencing)
Once the pointer exists, using the asterisk in front of it without a type name performs a different action called dereferencing. This is the act of following the address to see what is stored there.
If p is the business card, *p is the act of actually driving to the office and looking inside. If you change *p, you aren't changing the address stored in the card; you are changing the person sitting in the office.
int age = 25;
int *p = &age;
printf("%d", *p); // DEREFERENCING: Prints 25
*p = 30; // DEREFERENCING: Changes the value of age to 30
The Mental Shortcut
To keep these straight, look at what is to the left of the variable:
- If there is a type (like
int *), you are building a pointer. - If there is no type (just
*pin an equation), you are traveling through the pointer to the value it points to.
Key takeaway
int *p creates a pointer variable that stores an address, while *p follows that address to access or modify the actual value.