The asterisk (*) declares a pointer in C. In a declaration such as int *p;, the asterisk tells the compiler that p holds the address of an int. The other two symbols that come up with pointers, & and ->, don’t declare pointers. They do different jobs, and each is covered below.
The asterisk declares a pointer
Put the asterisk in front of the variable name in a declaration:
int *p; /* p is a pointer to int */
char *name; /* name is a pointer to char */
The spacing doesn’t change the meaning. int *p, int* p and int * p all declare the same thing. Pick one style and use it consistently.
Watch out when one declaration names more than one variable. In int *a, b;, only a is a pointer. b is a plain int. Declaring each pointer on its own line avoids the mix-up.
The same asterisk reads a pointer’s value
In an expression, the asterisk is the dereference operator. It reads the value stored at the address a pointer holds:
#include <stdio.h>
int main(void) {
int count = 5;
int *p = &count; /* the * here declares p; the & takes the address of count */
printf("%d\n", *p); /* this * reads the value p points to: 5 */
return 0;
}
The same symbol does two jobs. In a declaration, it declares a pointer. In an expression, it reads through one.
The ampersand takes an address
In an expression, & is the address-of operator. &count gives the address of count. It doesn’t declare a pointer.
C doesn’t use & in declarations at all. C++ does: int &r = count; declares a reference, which is a different feature that C doesn’t have.
The arrow reads a member through a pointer
-> isn’t used in declarations either. It reads a member of a struct through a pointer to that struct:
#include <stdio.h>
struct Point {
int x;
int y;
};
int main(void) {
struct Point pt = {3, 4};
struct Point *pp = &pt; /* the * declares pp as a pointer to a Point */
printf("%d\n", pp->x); /* -> reads x through pp: 3 */
return 0;
}
pp->x means the same as (*pp).x. The arrow is shorthand for that form.
The asterisk also declares function pointers
A pointer to a function is declared with the asterisk inside parentheses:
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int main(void) {
int (*fp)(int, int) = add; /* the * inside the parentheses declares fp as a function pointer */
printf("%d\n", fp(2, 3)); /* prints 5 */
return 0;
}
The parentheses matter. Without them, int *fp(int, int) declares a function that returns an int *, not a pointer to a function.
Quick reference
| Symbol | In a declaration | In an expression |
|---|---|---|
* |
Declares a pointer | Reads the value the pointer points to |
& |
Not used in C | Gives the address of a variable |
-> |
Not used | Reads a struct member through a pointer |
Summary
The asterisk is the symbol that declares a pointer in C. The ampersand takes the address of a variable, and the arrow reads a struct member through a pointer. Neither of those two declares a pointer.