The Array-Pointer Connection
In C, the relationship between an Array and a Pointer is the foundation of efficient memory management. Here is a clear breakdown of how they interact at a fundamental level.
1. The Hidden Identity
The most important rule in C is this: The name of an array is a pointer to its first element.
When you define int arr[5];, the identifier arr acts as a constant pointer that holds the memory address of arr[0].
- The "Base Address": This is the starting point of the array in RAM.
- The Identity: To the compiler, the name
arris equivalent to writing&arr[0].
2. Pointer Arithmetic (Scaling Logic)
Pointers are "type-aware." When you increment a pointer, it does not move by a single byte; it moves by the size of the data type it points to.
- If
ptrpoints to an integer (4 bytes),ptr + 1moves the address forward by exactly 4 bytes. - This ensures the pointer always lands perfectly at the start of the next element in the array.
3. Syntax Equivalence
In C, the square bracket notation [] is actually a "wrapper" for pointer arithmetic. The two columns below are mathematically identical to the computer:
| Action | Array Notation | Pointer Notation |
| Access Element 0 | arr[0] | *arr |
| Access Element "i" | arr[i] | *(arr + i) |
| Get Address of "i" | &arr[i] | (arr + i) |
Prof. Echo’s Insight: When you writearr[3], the computer literally calculates*(arr + 3)behind the scenes.
4. Critical Differences
While they share the same logic, there are two major technical differences to keep in mind:
- Modifiability: An array name is a constant pointer. You cannot change where it points (e.g.,
arr++is an error). A pointer is a variable, so it can move freely (ptr++is valid). - Size: *
sizeof(arr)returns the memory used by the entire array.sizeof(ptr)returns only the memory used to store the address (usually 4 or 8 bytes).
5. Why This Matters
When an array is passed to a function, it "decays" into a pointer. C does not copy the entire array to the function (which would be slow and memory-intensive); it only passes the address of the first element. This allows the function to access and modify the original data directly.
Summary
- Array: A fixed block of memory.
- Pointer: A variable that holds the address of memory.
- The Link: The array name provides the starting address that the pointer uses to navigate.
