What are * and & in C?
In C, * and & are pointer operators. & gives you the memory address of a variable. * has two jobs. In a declaration such as int *p, it says that p is a pointer. In an expression such as *p, it reads or changes the value stored at the address p holds.
A complete example
#include <stdio.h>
int main(void) {
int age = 30;
int *p = &age; // p holds the address of age
printf("%d\n", age); // 30
printf("%d\n", *p); // 30, read through the pointer
*p = 31; // write through the pointer
printf("%d\n", age); // 31
return 0;
}
Output:
30
30
31
Changing *p changed age, because p points to age. Both names refer to the same memory.
The & operator
&age produces the address of age. You use that address to create a pointer, as int *p = &age; does above. The address is a number that depends on your system, so you rarely need to print it.
In C, a unary & in an expression means “address of”. In C++, & can also appear in a declaration such as int &r = age;, which creates a reference, a second name for the same variable. C has no references, so that form does not compile in C.
The * operator has three meanings
- Pointer declaration:
int *p;declarespas a pointer to anint. Spacing does not matter to the compiler, soint *pandint* pmean the same thing. - Dereference:
*pin an expression accesses the value at the address thatpholds. - Multiplication:
a * bmultiplies two numbers. The surrounding code shows which meaning applies.
Be careful with several names in one declaration. In int *a, b;, only a is a pointer. b is a plain int.
Common mistakes
- Dereferencing an uninitialized pointer.
int *p;without a value holds an unknown address. Using*pbeforeppoints to a real object is undefined behavior. - Dereferencing NULL. Using
*pwhenpis a null pointer is also undefined behavior, and usually crashes. Check thatp != NULLbefore using it whenever a null pointer is possible. - Assigning to the pointer instead of the value.
p = 31;changes the address stored inp, not the value it points to. Use*p = 31;to change the value. The compiler will usually warn aboutp = 31, or reject it, because anintis not a pointer.
Where pointers come up next
Pointers show up when you pass arrays to functions, and those rules are covered in how to pass an array to a function in c. A pointer that points at nothing needs a special null value, which is covered in c null vs nullptr.