What is ‘array decaying’ in C?

It is sometimes said that arrays in C are basically pointers. This is not true. What is true is that a value of an array type can decay to a value of a pointer type.

Take this:

#include <stdio.h>

void takes_arr_pointer_1(int* arr) {
  printf("in takes_arr_pointer_1, sizeof(arr) = %d\n", sizeof(arr));
}

void takes_arr_pointer_2(int arr[]) {
  printf("in takes_arr_pointer_2, sizeof(arr) = %d\n", sizeof(arr));
}

int main() {
  int arr[100];
  printf("in main, sizeof(arr) = %d\n", sizeof(arr));
  takes_arr_pointer_1(arr);
  takes_arr_pointer_2(arr);
  return 0;
}

This prints:

% ./a.out
in main, sizeof(arr) = 400
in takes_arr_pointer_1, sizeof(arr) = 8
in takes_arr_pointer_2, sizeof(arr) = 8

In the context of main, the arr variable is an array of 100 ints. On my machine, sizeof(int) = 4, so sizeof(arr) = 400.

In the context of both other functions, the arr variable is a pointer to an int. Thus, sizeof(arr) is the size of a pointer, which on my machine is 8 bytes.

We were able to pass the int arr[100] to both functions, even though they accept pointers. The conversion of arr from an array type to a pointer type is known as array decaying, i.e. the array has “decayed” to a pointer.

The two parameter definitions int* arr and int arr[] are actually the same. Perhaps this is where the confusion comes from.

I just released Vidrio, a free app for macOS and Windows to make your screen-sharing awesomely holographic. Vidrio shows your webcam video on your screen, just like a mirror. Then you just share or record your screen with Zoom, QuickTime, or any other app. Vidrio makes your presentations effortlessly engaging, showing your gestures, gazes, and expressions. #1 on Product Hunt. Available for macOS and Windows.

With Vidrio

With generic competitor

More by Jim

Tagged . All content copyright James Fisher 2016. This post is not associated with my employer. Found an error? Edit this page.