Learn more about Russian war crimes in Ukraine.

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.

What can computers do? What are the limits of mathematics? And just how busy can a busy beaver be? This year, I’m writing Busy Beavers, a unique interactive book on computability theory. You and I will take a practical and modern approach to answering these questions — or at least learning why some questions are unanswerable!

It’s only $19, and you can get 50% off if you find the discount code ... Not quite. Hackers use the console!

After months of secret toil, I and Andrew Carr released Everyday Data Science, a unique interactive online course! You’ll make the perfect glass of lemonade using Thompson sampling. You’ll lose weight with differential equations. And you might just qualify for the Olympics with a bit of statistics!

It’s $29, but you can get 50% off if you find the discount code ... Not quite. Hackers use the console!

More by Jim

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