Search code examples
arrayscsizeofdivide

In C, why is the sizeof function used as the denominator to store the number of elements in an array?


More than once I have seen the sizeof operator used on index 0 of an array act as the denominator when storing the number of elements of an array. My question is why use the sizeof operator instead of just dividing by 1 or not dividing at all?

See an example of this phenomenon below in some sample code from https://www.bravegnu.org/gnu-eprog/c-startup.html.

static int arr[] = { 1, 10, 4, 5, 6, 7 };
static int sum;
static const int n = sizeof(arr) / sizeof(arr[0]);  //RIGHT HERE!!!!!

int main()
{
        int i;

        for (i = 0; i < n; i++)
                sum += arr[i];
}

Solution

  • static int arr[] = { 1, 10, 4, 5, 6, 7 };
    

    Array arr is a bunch of integers, six of them to be precise. Each integer takes up some number of bytes (let's assume four for the purposes of this answer - on some systems it can be more or less).

    So, sizeof(arr) is 24 bytes, six integers times four bytes each.

    If you want to know how many elements (rather than bytes) are in the array, divide the size of the entire array by the size of a single member, one of:

    static const int n = sizeof(arr) / sizeof(arr[0]);
    static const int n = sizeof(arr) / sizeof(*arr);
    
    // sizeof(arr) / sizeof(arr[0]) == 24 / 4 == 6 elements