Pointers and Arrays
Arrays and pointers are closely related in C programming. In fact, they're so connected that understanding their relationship is crucial for mastering C!
Array Names as Pointers
When you declare an array, the array name acts as a pointer to the first element of the array. Think of it like this: if your array is a row of houses, the array name is the address of the first house.
int numbers[5] = {10, 20, 30, 40, 50};
// 'numbers' points to the address of numbers[0]
Pointer Arithmetic with Arrays
You can use pointer arithmetic to navigate through array elements:
#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
int *ptr = arr; // ptr points to first element
printf("First element: %d\n", *ptr); // Output: 1
printf("Second element: %d\n", *(ptr + 1)); // Output: 2
printf("Third element: %d\n", *(ptr + 2)); // Output: 3
return 0;
}
Array Subscript vs Pointer Notation
These two notations are equivalent in C:
| Array Notation | Pointer Notation | Description |
|---|---|---|
arr[0] | *arr or *(arr + 0) | First element |
arr[1] | *(arr + 1) | Second element |
arr[i] | *(arr + i) | i-th element |
#include <stdio.h>
int main() {
int data[4] = {100, 200, 300, 400};
// Both ways access the same elements
printf("Using array notation: %d\n", data[2]); // Output: 300
printf("Using pointer notation: %d\n", *(data + 2)); // Output: 300
return 0;
}
Passing Arrays to Functions
When you pass an array to a function, you're actually passing a pointer to the first element:
#include <stdio.h>
void printArray(int *arr, int size) {
for(int i = 0; i < size; i++) {
printf("%d ", arr[i]); // or *(arr + i)
}
printf("\n");
}
int main() {
int numbers[5] = {5, 10, 15, 20, 25};
printArray(numbers, 5); // Pass array to function
return 0;
}
Dynamic Memory and Arrays
You can create arrays dynamically using pointers and malloc():
#include <stdio.h>
#include <stdlib.h>
int main() {
int size = 5;
int *dynamicArray = (int*)malloc(size * sizeof(int));
// Fill the array
for(int i = 0; i < size; i++) {
dynamicArray[i] = i * 10;
}
// Print the array
for(int i = 0; i < size; i++) {
printf("%d ", dynamicArray[i]);
}
free(dynamicArray); // Don't forget to free memory!
return 0;
}
Key Points to Remember
- Array names are pointers to the first element
arr[i]is equivalent to*(arr + i)- When passing arrays to functions, you're passing pointers
- Pointer arithmetic allows you to navigate through array elements
- Dynamic arrays are created using pointers and memory allocation functions
Understanding the relationship between pointers and arrays opens up powerful programming techniques and helps you write more efficient C code!