Element count of an array in C++

前端 未结 11 1750
[愿得一人]
[愿得一人] 2020-12-05 10:38

Let\'s say I have an array arr. When would the following not give the number of elements of the array: sizeof(arr) / sizeof(arr[0])?

I can

11条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-05 11:03

    There are no cases where, given an array arr, that the value of sizeof(arr) / sizeof(arr[0]) is not the count of elements, by the definition of array and sizeof.

    In fact, it's even directly mentioned (§5.3.3/2):

    .... When applied to an array, the result is the total number of bytes in the array. This implies that the size of an array of n elements is n times the size of an element.

    Emphasis mine. Divide by the size of an element, sizeof(arr[0]), to obtain n.

提交回复
热议问题