In C, the names of arrays are deeply intertwined with pointers. In most contexts, an array name is treated as a constant pointer to the address of its first element. This equivalence is fundamental to C programming.
1. The Array Name as a Pointer
When you use an array name without brackets ([]), it automatically decays into a pointer to the first element.
Consider an array:
int data[5] = {10, 20, 30, 40, 50};
The following three expressions all represent the same memory address (the start of the array):
data
&data[0]
(int *)data
2. Accessing Elements Using Pointers
Because of this equivalence, you can access array elements using standard pointer notation instead of array indexing ([]).
| Method | Syntax | Explanation |
| Array Indexing | data[i] | Accesses the element at index i. |
| Pointer Notation | *(data + i) | Accesses the element found at the address that is i memory locations after the starting address of data. |
Example: Pointer Notation Access
int numbers[3] = {100, 200, 300};
// Accessing the second element (index 1)
int value1 = numbers[1]; // value1 is 200 (standard method)
int value2 = *(numbers + 1); // value2 is 200 (pointer method)
3. Pointer Arithmetic
When performing arithmetic on a pointer, C automatically scales the calculation by the size of the data type the pointer points to. This is called pointer arithmetic.
- If
ptris a pointer to anint(typically 4 bytes), adding 1 to the pointer (ptr + 1) doesn’t add 1 byte; it moves the pointer forward by 1 unit of the data type (4 bytes) to point exactly to the next integer in memory. ptr + imoves the pointer $i \times \text{sizeof(dataType)}$ bytes forward.
Example of Pointer Increment
int arr[] = {10, 20, 30};
int *ptr = arr; // ptr points to arr[0] (value 10)
printf("Value at arr[0]: %d\n", *ptr);
ptr++; // Pointer arithmetic moves ptr to arr[1] (20)
printf("Value at arr[1]: %d\n", *ptr);
// If 'arr' started at memory 1000, 'ptr' moved to 1004.
4. Arrays as Function Arguments
When you pass an array to a function, C always passes it by reference (meaning the function gets access to the original memory block). Even if the function signature uses array notation, the compiler treats the parameter as a pointer.
// The parameter declaration is identical to: void process(int *arr)
void processArray(int arr[], int size) {
arr[0] = 99; // Changes the original array in main()
}
int main() {
int scores[5] = {1, 2, 3, 4, 5};
processArray(scores, 5); // Pass the array name (pointer to first element)
printf("New score: %d\n", scores[0]); // Output: 99
return 0;
}
