Creating and Using Pointers
Get a pointer from a variable with the & operator:
- If
vis a variable, then&vis a pointer referring to all the memory forv.
Get a pointer to part of a composite variable by writing an expression to access that part,
then use the & operator.
- If
chairis a structure with memberlegsthat is an array of 4 values, then&chair.legs[3]is a pointer to the last leg in the chair.
To access the memory a pointer refers to, use the * operator to turn the pointer into a reference.
- If
pis a pointer then*pis a reference to the same memory.
Assignments write to the reference appearing on their left hand side. Otherwise, a reference will be read from.
*p = 12;writes 12 to the memory locationsppoints to.x = *p;reads the value pointed to bypand writes it to x.