Pointer-Array Relationship
Pointer-Array Relationship
1. Arrays and Pointers
Arrays and pointers are closely related in C.
An array is a collection of elements (like integers or characters) stored in contiguous memory locations.
A pointer is a variable that holds the memory address of another variable.
1.1. Array as a Pointer
When you use the name of an array, it acts like a pointer to the first element of the array. For example:
Here, numbers
is an array, and ptr
is a pointer pointing to the first element of numbers
.
1.2. Accessing Array Elements with Pointers
You can access array elements using pointers in two ways:
Using the array index notation:
numbers[i]
Using pointer arithmetic:
*(ptr + i)
Both of these access the same memory locations:
2. Pointer Arithmetic with Arrays
When working with arrays and pointers, pointer arithmetic becomes handy:
ptr + 1
moves the pointer to the next element.ptr - 1
moves the pointer to the previous element.*(ptr + n)
accesses then
-th element from the start.
3. Example: Traversing an Array
Here’s an example of traversing an array using a pointer:
4. Array of Pointers
You can also have an array of pointers. For example, an array of string pointers:
In this case, strings
is an array of pointers to strings.
Summary
An array name acts as a pointer to the first element.
You can access array elements using both array notation and pointer arithmetic.
Pointer arithmetic allows easy traversal of arrays.
You can have arrays of pointers, which are useful for managing multiple strings or other data.
Last updated
Was this helpful?