Size of the array without using sizeof operator

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]);Thatsizeofnonsense 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 :&arris a pointer to the array. It points at the same memory address asarr. Butarrdecays to a pointer to first element.That means&arr + 1points at the address after the end of the array.Dereferencing to*(&arr + 1)gives the address after the end of the last element (which is again the same address as&arr + 1with a different type; Similar toarrand&arras*&arris equivalent toarr).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).

News Reporter

Leave a Reply

Your email address will not be published. Required fields are marked *