CodeBlanks Logo Icon CodeBlanks

Array name as pointer

Learn that the array name is a pointer to the first element.

Array name as pointer

In C an array name decays into the address of its first element. So you can assign an array name directly to a pointer.

int arr[3] = {10, 20, 30};
int *p = arr;  /* p holds the address of arr[0] */
printf("%d", *p);  /* prints 10 */

This is called array decay: the array info drops to a pointer. arr and p now refer to the same memory region.

Array decay in functions

When you pass an array to a function the array name decays into a pointer. The function sees the array itself, not a copy. So the function can modify the array elements.

void add_one(int *arr, int n) {
    for (int i = 0; i < n; i++) arr[i]++;
}

The array length is not stored in the pointer; you must pass the size as a separate parameter.

Practice Access array elements via pointer

Define int arr[3] = {10, 20, 30};. Bind p to arr with int *p = arr;. With three printf calls print *p, *(p + 1) and *(p + 2) on separate lines. Output should be 10, 20, 30.

Starter code

main.c
#include <stdio.h>

int main(void) {
    int arr[3] = {10, 20, 30};
    /* bind p to arr; print *p, *(p+1), *(p+2) */
    return 0;
}

Sample solution

main.c
#include <stdio.h>

int main(void) {
    int arr[3] = {10, 20, 30};
    int *p = arr;
    printf("%d\n", *p);
    printf("%d\n", *(p + 1));
    printf("%d\n", *(p + 2));
    return 0;
}

Expected output

10
20
30

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 int arr[3] = {10,20,30}; printf("%d", *(arr+1)); prints what?

  • 10
  • 20 Correct answer
  • 30
  • 11

Explanation: *(arr+1) is arr[1], which is 20.

2 Assign array to pointer

Question
int arr[3] = {10, 20, 30};
int *p = ____;  /* p now points to arr */
Answer
int arr[3] = {10, 20, 30};
int *p = arr;  /* p now points to arr */

Explanation: You can assign an array name directly to a pointer.

3 Match array-pointer concepts

Term Meaning
arr address of first element
arr+1 address of second element
*(arr+2) value of third element
int *p = arr pointer assignment

All lessons in Beginner