In C programming, pointers are not only used to store addresses but also to access array elements efficiently using pointer arithmetic. This tutorial demonstrates how to access and print elements of an array using a pointer.
Objective
- Declare an array of integers.
- Use a pointer to access each element.
- Print both the value and its address.
Example C Program
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int *ptr;
int i;
ptr = arr; // Pointer to the first element of array
printf("Element | Address | Value\n");
printf("----------------------------\n");
for(i = 0; i < 5; i++) {
printf("arr[%d] | %p | %d\n", i, (ptr + i), *(ptr + i));
}
return 0;
}
Sample Output
Element | Address | Value
-------------------------------
arr[0] | 0x7ffeedfa81b0 | 10
arr[1] | 0x7ffeedfa81b4 | 20
arr[2] | 0x7ffeedfa81b8 | 30
arr[3] | 0x7ffeedfa81bc | 40
arr[4] | 0x7ffeedfa81c0 | 50
(Note: Memory addresses will vary with each run.)
Explanation
ptr = arr;
sets the pointer to the base address of the array.*(ptr + i)
accesses the value at indexi
using pointer arithmetic.(ptr + i)
is the address of the element at indexi
.
Pointer Concepts Used
- Pointer arithmetic: Traverse the array using
ptr + i
. - Dereferencing: Access values with
*(ptr + i)
. - Efficient memory traversal without using array indexing directly.
Key Takeaways
- Arrays and pointers are closely related in C.
- Pointer arithmetic allows faster, more flexible array manipulation.
- Ideal for working with dynamic arrays and memory buffers.
Conclusion
Using a pointer to access array elements demonstrates the power and flexibility of C pointers. Whether you’re optimizing performance or working with dynamic memory, this approach is essential for any serious C programmer.