We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Arrays Decay to Pointers

So we know that arrays are like pointers, but they're not exactly the same. Arrays allocate memory for all their elements, whereas pointers just hold the address of a memory location. In many contexts, arrays decay to pointers, meaning the array name becomes "just" a pointer to the first element of the array.

When Arrays Decay

Arrays decay when used in expressions containing pointers:

int arr[5];

// 'arr' decays to 'int*' because that's the type of 'ptr'
int *ptr = arr;

// 'arr' decays to 'int*' to perform pointer arithmetic
int value = *(arr + 2);

And also when they're passed to functions... so they actually decay quite often in practice. That's why you can't pass an array to a function by value like you do with a struct; instead, the array name decays to a pointer.

When Arrays Don't Decay

  • sizeof Operator: Returns the size of the entire array (e.g., sizeof(arr)), not just the size of a pointer.
  • & Operator: Taking the address of an array with &arr gives you a pointer to the whole array, not just the first element. The type of &arr is a pointer to the array type, e.g., int (*)[5] for an int array with 5 elements.
  • Initialization: When an array is declared and initialized, it is fully allocated in memory and does not decay to a pointer.

Assignment

Take a look at the main function. It declares an array of numbers core_utilization that represents the CPU utilization of each core on a system running the Sneklang interpreter. The array has 8 elements. On lines 12 and 13 it prints the size of the array and the length of the array.

Complete the core_utils_func function to print:

sizeof core_utilization in core_utils_func: X

Where X is the size of the array calculated using the sizeof operator.

Once you've completed the function, run it and take a look at the output. You'll notice that due to the array decaying to a pointer, the reported size is the size of a pointer, not the size of the actual array.