đ Pointers and Arrays in C
In C programming, arrays and pointers are closely related. Understanding how they interact is essential for mastering C. This tutorial explains how pointers work with arrays, with step-by-step examples.
đ Relationship Between Arrays and Pointers
When you declare an array, the array name itself acts as a pointer to the first element.
int arr[5] = {10, 20, 30, 40, 50};
Here, arr
is equivalent to &arr[0]
.
đ Accessing Array Elements Using Pointers
#include <stdio.h>
int main() {
int arr[5] = {10, 20, 30, 40, 50};
int *p = arr; // same as p = &arr[0]
for(int i = 0; i < 5; i++) {
printf("Element %d: %d\n", i, *(p + i));
}
return 0;
}
đ§Ē Output:
Element 0: 10 Element 1: 20 Element 2: 30 Element 3: 40 Element 4: 50
Explanation: p + i
points to the i-th element, and *(p + i)
accesses the value.
đ Pointer Notation vs Array Notation
Array Notation | Pointer Notation |
---|---|
arr[i] |
*(arr + i) |
*(p + i) |
p[i] |
All these expressions are equivalent when working with 1D arrays.
đ Modifying Arrays Using Pointers
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 5};
int *p = arr;
for(int i = 0; i < 5; i++) {
*(p + i) = *(p + i) * 2; // double each element
}
for(int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
return 0;
}
đ§Ē Output:
2 4 6 8 10
⚠️ Important Notes
arr
points to the first element, but it is a constant pointer – you cannot modify it witharr++
.p = arr
is allowed, andp++
is valid.
đ§Š Practice Exercises
- Write a program to calculate the sum of all elements in an array using a pointer.
- Reverse an array using pointer notation.
- Find the maximum and minimum values in an array using pointers.
- Write a program to copy one array to another using pointers.
đ§ Summary
arr
is equivalent to&arr[0]
.arr[i] == *(arr + i)
andp[i] == *(p + i)
.- Pointers offer a flexible and powerful way to work with arrays.
āĻোāύ āĻŽāύ্āϤāĻŦ্āϝ āύেāĻ:
āĻāĻāĻি āĻŽāύ্āϤāĻŦ্āϝ āĻĒোāϏ্āĻ āĻāϰুāύ