Pointers & Memory · beginner · ~8 min
Read and change one live int through a pointer; distinguish the pointer from its target.
A pointer stores a reference to an object. Start with one local integer and a pointer to it. In this lesson you will distinguish the value of the integer, the address held by the pointer, and the value read through that address. You do not need allocation, linked lists, or double pointers yet.
int x = 7; creates an integer object. int *p = &x; makes p point to it. In a declaration, * is part of the pointer declarator; in an expression, *p accesses the pointed-to object.
Writing *p = 12 changes x. Assigning a different address to p instead changes which object you access. These are different operations.
p ──points to──> x: 7
*p = 12 x: 12
Use only pointers to live objects of an appropriate type. A null pointer, an uninitialized pointer, or a pointer to an expired object must not be dereferenced. A null check alone does not prove a pointer is valid.
A pointer stores a reference to an object. Start with one local integer and a pointer to it. In this lesson you will distinguish the value of the integer, the address held by the pointer, and the value read through that address. You do not need allocation, linked lists, or double pointers yet.
#include <stdio.h>
int main(void) {
int x = 7;
int *p = &x;
*p = 12;
printf("%d %d\n", x, *p);
return 0;
}
Expected output on a successful allocation, where applicable:
12 12
p receives the address of x. The assignment through p changes that same object. Both arguments to printf therefore read 12.
p points to a second integer; predict which integer a write through p changes.Use &x to obtain an address and *p to access its target. Changing p and changing *p are different actions. Keep the target alive for every access. Next, learn which pointer movements stay inside an array.