A pointer value is the address of an object (or a function, or null). The pointer’s type says how to interpret the bytes at that address and how far + 1 moves.
int n = 7; int *p = &n; /* p holds the address of n */ *p = 8; /* n is now 8 */
Mental model: n is a box of bits. &n is the box’s address. *p means “the object at this address.” Assignment to p changes which box you mean. Assignment to *p changes the box’s contents.
int *p; /* p is a pointer to int */ int* p, q; /* q is an int, not a pointer — * binds to the name */ int *p, *q; /* two pointers */
int *p so the star sits with the name. One declaration per line if you mix types.NULL or a real address first.NULL is a null pointer constant (from <stddef.h> / stdio.h). Dereferencing it is undefined.| Op | Meaning |
|---|---|
&x | Address of x (x must be an lvalue; you cannot take &42) |
*p | Object pointed to (dereference) |
p->m | (*p).m — member of a struct through a pointer |
void bump(int *p) {
if (p == NULL) {
return;
}
*p += 1;
}
C is pass-by-value. To let a function change the caller’s object, pass its address. To change the caller’s pointer (for example re-seat it), pass a pointer to pointer: int **.
p + 1 points to the next object of the pointed-to type, not the next byte (unless char *).
int a[3] = {1, 2, 3};
int *p = a; /* &a[0] */
*(p + 2) == a[2];
ptrdiff_t.void * is a generic object pointer. You cannot dereference it. Convert explicitly to a typed pointer before use. Function pointers are not void * in portable C.const int *p — the int is const through this pointer. int *const p — the pointer itself cannot be reseated.char” historically; writing through a pointer to a literal is undefined. Treat them as const char *.const char *s = "hi"; /* s[0] = 'H'; undefined */
* and & the wrong way around until the program “works” on one test.int *p = n; without & — converting an int to a pointer (implementation-defined / wrong).* unless a documented precondition forbids NULL.const on the pointee when the function does not mutate it.~ Good luck with your revision! ~