Introduction to pointers

suggest change

A pointer stores a value that identifies an object or function, or a distinguished null value. Declare a pointer by placing * with each declarator:

int *first;
int *second, value; /* second is a pointer; value is an int. */

An uninitialized automatic pointer has an indeterminate value and must not be read. Initialize pointers immediately when practical:

int value = 42;
int *pointer = &value;
int *nothing = NULL;

The unary & operator obtains an address. The unary * operator dereferences a pointer to access the pointed-to object:

printf("%d\n", *pointer);
*pointer = 43;

Dereferencing is valid only while the pointer identifies a live object and the access satisfies the object's type, alignment, bounds, and effective-type requirements. A null pointer, dangling pointer, one-past pointer, or arbitrary representation must not be dereferenced.

For a pointer to a structure or union, -> combines dereference and member access:

struct point {
    int x;
    int y;
};

struct point origin = {0, 0};
struct point *point = &origin;
point->x = 10; /* Equivalent to (*point).x = 10. */

Print an object pointer by converting it to void * and using %p:

printf("address: %p\n", (void *)pointer);

The representation and printed form are implementation-defined. Do not assume that pointers have the same size as int, that every kind of pointer has the same size, or that an address is stable between program executions.

Pointers and arrays

Array elements are contiguous. In most expressions, an array is converted to a pointer to its first element:

double coordinates[3] = {0.0, 1.0, 2.0};
double *cursor = coordinates;

printf("%.1f\n", cursor[1]); /* Prints 1.0. */

Pointer arithmetic is scaled by the pointed-to type. If cursor points into coordinates, then cursor + 1 points to the next element.

A pointer may be formed to an array element or one position past the final element. A one-past pointer is useful as a loop boundary but must not be dereferenced. Pointer arithmetic outside that range has undefined behavior.

Arrays and pointers are related but not interchangeable. An array object owns all its elements and usually has a size known in its defining scope. A pointer is a separate object that can be reassigned. Applying sizeof to an array yields the array's size; applying it to a pointer yields the pointer's size.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents