Lesson 17 of 31
Pointers and Arrays
Pointers and Arrays
In C, arrays and pointers are closely related. An array name, in most contexts, decays to a pointer to its first element.
Array Decay
int arr[5] = {10, 20, 30, 40, 50};
int *p = arr; // arr decays to &arr[0]
Now p[i] and arr[i] access the same memory. You can use pointer arithmetic or array indexing interchangeably:
printf("%d\n", p[2]); // 30
printf("%d\n", *(p + 2)); // 30 (same thing)
Tractor beam arrays: multiple beams working in concert, each pointing to a different target. That's pointer arithmetic in action.
Arrays as Function Parameters
When you pass an array to a function, it decays to a pointer. The function receives a pointer, not a copy:
void print_array(int *arr, int len) {
for (int i = 0; i < len; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int nums[] = {1, 2, 3};
print_array(nums, 3);
}
Modifying Arrays Through Pointers
Since the function gets a pointer to the original array, it can modify the array:
void double_elements(int *arr, int len) {
for (int i = 0; i < len; i++) {
arr[i] = arr[i] * 2;
}
}
Your Task
Write a function void reverse(int *arr, int len) that reverses an array in place. Call it on {1, 2, 3, 4, 5} and print each element separated by spaces.
TCC compiler loading...
Loading...
Click "Run" to execute your code.