A pointer is an object that stores the address of another object or function.
int number = 25;
int *ptr = &number;
printf("%d\n", number); // 25
printf("%p\n", (void *)ptr); // address
printf("%d\n", *ptr); // 25&numberobtains the address ofnumber.int *ptrdeclares a pointer toint.*ptrdereferences the pointer to access the pointed-to object.
int number = 25;
int *ptr = &number;
*ptr = 50;
printf("%d\n", number); // 50void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
/* call: swap(&x, &y); */A null pointer points to no object. Initialize pointers when no valid target is available:
int *ptr = NULL;
if (ptr != NULL) {
printf("%d\n", *ptr);
}Never dereference a null, uninitialized, dangling or otherwise invalid pointer.
In many expressions, an array name converts to a pointer to its first element. This does not mean arrays and pointers are identical types.
int values[] = {4, 8, 12};
int *p = values;
printf("%d\n", *(p + 1)); // 8Pointer arithmetic is only defined within the same array object (or one position past its end); the one-past pointer must not be dereferenced.
- Using
*ptrbefore assigning a valid address. - Returning the address of a local automatic variable.
- Dereferencing after the pointed-to object's lifetime ends.
- Confusing
int *p(pointer declaration) with*p(dereference in an expression).
- Swap two numbers using pointers.
- Find the sum of an array using pointer traversal.
- Explain the difference between
p,&pand*p.