Pointers
Pointers are a fundamental and powerful feature in C that let you work directly with memory. They can seem a bit tricky at first, but they’re incredibly useful once you get the hang of them.
What is a Pointer?
A pointer is a variable that stores the address of another variable. Instead of holding a data value, a pointer holds the location of that value in memory.
Pointer Basics
Declaration: You declare a pointer by specifying the type of data it points to, followed by an asterisk
*
.Initialization: You assign a pointer the address of a variable using the address-of operator
&
.Dereferencing: To access the value stored at the address a pointer points to, you use the dereference operator
*
.
Pointer Example
Here’s a simple example showing how pointers work:
Explanation:
int *ptr = &x;
initializes the pointerptr
with the address ofx
.*ptr
is used to access the value ofx
through the pointer.
Pointer Arithmetic
Pointers can be incremented or decremented to point to different memory locations. This is especially useful with arrays.
Example: Pointer Arithmetic with Arrays
Explanation:
ptr + 1
moves the pointer to the next integer (4 bytes away in most systems).*(ptr + 1)
accesses the second element of the array.
Dynamic Memory Allocation
Pointers are used to allocate memory dynamically at runtime using functions from the <stdlib.h>
library.
Functions:
malloc(size_t size)
: Allocates memory.free(void *ptr)
: Frees allocated memory.calloc(size_t num, size_t size)
: Allocates memory and initializes it to zero.realloc(void *ptr, size_t newSize)
: Resizes previously allocated memory.
Example: Using malloc
and free
Explanation:
malloc
allocates memory on the heap.Always check if
malloc
returnsNULL
to handle memory allocation failures.free
releases the allocated memory to avoid memory leaks.
Pointers and Functions
Pointers can be passed to functions to allow modifications to the original data or to handle large amounts of data efficiently.
Example: Modifying Data Using Pointers
Explanation:
increment(&num)
passes the address ofnum
to the function.(*p)++
modifies the value ofnum
through the pointer.
Pointers to Pointers
A pointer to a pointer is a variable that stores the address of another pointer.
Example:
Explanation:
ptr
is a pointer tox
.pptr
is a pointer toptr
.
Summary
Pointers store addresses of variables.
Dereferencing
*
accesses the value at the pointer’s address.Pointer Arithmetic allows moving through arrays.
Dynamic Memory Allocation uses
malloc
,calloc
,realloc
, andfree
.Pointers in Functions enable modifications to original data.
Pointers to Pointers involve multiple levels of indirection.
Last updated
Was this helpful?