- Asked 5/16
- 2069 Asar · 3 marks
- 2070 Chaitra · 5 marks
- 2071 Chaitra · 4 marks
- 2070 Asar · 3 marks
- 2069 Chaitra · 3 marks
Relation between array and pointer
How are array and pointer related? Compare array and pointer with example. (Illustrate with example that "array is indirectly a pointer".)
Relation between array and pointer
In C, the name of an array is the address of its first element (a constant pointer). If int a[4] and int *p = a;, then p holds &a[0]. Because of this:
a[i]is exactly the same as*(a + i), andp[i]is the same as*(p + i).a + iis the address of the i-th element. Adding 1 to a pointer moves it bysizeofthe element type (4 bytes forint).- Arrays are passed to functions as pointers, so the function can change the original data.
So an array is "indirectly a pointer", and pointer arithmetic is used to walk through it.
#include <stdio.h>
int main(void)
{
int a[4] = {10, 20, 30, 40};
int *p = a; /* same as &a[0] */
for (int i = 0; i < 4; i++)
printf("a[%d]=%d *(a+%d)=%d p[%d]=%d *(p+%d)=%d\n",
i, a[i], i, *(a + i), i, p[i], i, *(p + i));
printf("sizeof(a) = %zu, sizeof(p) = %zu\n", sizeof a, sizeof p);
return 0;
}
Output:
a[0]=10 *(a+0)=10 p[0]=10 *(p+0)=10
a[1]=20 *(a+1)=20 p[1]=20 *(p+1)=20
a[2]=30 *(a+2)=30 p[2]=30 *(p+2)=30
a[3]=40 *(a+3)=40 p[3]=40 *(p+3)=40
sizeof(a) = 16, sizeof(p) = 8
Comparison
| Basis | Array | Pointer |
|---|---|---|
| Meaning | Block of same-type elements | Variable holding an address |
| Memory | Fixed size set at declaration | Only the address is stored (8 bytes here); data stored elsewhere |
| Assignment | Name cannot be changed (a = a + 1 is an error) | Can point to other places (p++) |
sizeof | Whole array (16 bytes above) | Size of the pointer (8 bytes here) |
| Allocation | Allocated automatically | Can use malloc() to get memory at run time |
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Reverse array and display via pointer · Computer Programming, chapter 9
- Accessing array elements using pointer · Computer Programming, chapter 9
- Copy string converting lower to upper using pointer · Computer Programming, chapter 9 · asked 3×
- Second largest element using pointer · Computer Programming, chapter 9
- Pointers in pass by reference; 2D array · Computer Programming, chapter 9
- Pattern lobes and 180° out-of-phase array · Propagation and Antenna, chapter 2
- Two-element array: broadside and end fire · Propagation and Antenna, chapter 2
- Two-element array and end fire pattern · Propagation and Antenna, chapter 2
- Flywheel energy relation and rim sizing · Theory of Mechanism and Machine II, chapter 2