17
Size of the array without using sizeof operator
C
C++
Arrays
Pointers

Consider an array defined as :

int arr[] = {1, 2, 5, 8, 3, 1, 4};

How do you calculate its size?

size_t arr_size = sizeof(arr) / sizeof(arr[0]);

That sizeofnonsense is ugly, and it’s often hidden behind a macro. But we can simplify it using pointer arithmetic.

This is how we do it :

size_t arr_size = *(&arr + 1) - arr;

If you're wondering how does it work, go on :

  1. &arr is a pointer to the array. It points at the same memory address as arr. But arr decays to a pointer to first element.

  2. That means &arr + 1 points at the address after the end of the array.

  3. Dereferencing to *(&arr + 1) gives the address after the end of the last element (which is again the same address as &arr + 1 with a different type; Similar to arr and &arr as *&arr is equivalent to arr).

  4. Finally, we can subtract the pointer to the first element to get the length of the array :
    *(&arr + 1) - arr. (Remember this is pointer arithmetic; Subtraction gives the total number of objects between them).


Author

Notifications

?