Skip to main content

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), and p[i] is the same as *(p + i).
  • a + i is the address of the i-th element. Adding 1 to a pointer moves it by sizeof the element type (4 bytes for int).
  • 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

BasisArrayPointer
MeaningBlock of same-type elementsVariable holding an address
MemoryFixed size set at declarationOnly the address is stored (8 bytes here); data stored elsewhere
AssignmentName cannot be changed (a = a + 1 is an error)Can point to other places (p++)
sizeofWhole array (16 bytes above)Size of the pointer (8 bytes here)
AllocationAllocated automaticallyCan use malloc() to get memory at run time

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 9 questions →