Pointers store addresses of variables. You can think of memory as a long table with 2 columns.
| address | opcode | # explaination (not found in memory) |
|---|---|---|
| 01 | “hi” | # variable at address 01 storing “hi” |
| 02 | 21 | # variable at address 02 storing 21 |
| 02 | address 02 | # this is a pointer, address 02 |
Pointer variables store the address of other variables, which can then be accessed, modified, freed etc.
Because the range of values a pointer can take differs from the range of values an integer can take, we need the new kind of variable, pointer variables.
To declare a pointer variable, we have to precede the name with an asterisk
In the above, int is the referenced type.
* ~= &−1 see:
[[operator___20240603_115338#address operator|address operator]]
int i, j, *p, *q;
p = &i;
q = p; // both q and p point to i.
*q = *p; // the value that p points to is copied to the object that q points to.int *p;
printf("%d", *p); // undefined behaviour
*p = 1 // attempts to modify an abitrary mem addressq = p and *q = *p*q = *p := Copy the value that
p points to into the object that q points to.
The indirection operator
is used here.q = p := when both are pointers,
q = p is setting q as an alias for
p. What is stored in p (an address) is now
stored in q.const in front of it.
e.g. void f(const int *p);Consider a computer whose memory is divided into words rather than bytes. For sake of argument, suppose a word has 36 bits. When memory is divided into words, each word has an address. But a variable doesn’t fall perfectly into 1 word all the time. e.g. a character might be 9 bits. But the character needs a pointer, which may hold an address and the offset.
max can return a pointer passed into it, but also a
pointer to an external variable or to a local variable that is
static.
Never return a pointer to an automatic variable
int *f(void)
{
int i;
return &i; // i doesn't exist when f returns, so the pointer will be invalid
}void f(const int *p) means that you cannot change the
value at p but you can change the pointer
(p = &j;)void f( int * const p) means that you can change the
value at p but you cannot change the pointer
(*p = 0;)see also link_between_pointers_and_array