Element count of an array in C++

前端 未结 11 1765
[愿得一人]
[愿得一人] 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:06

    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])?

    In contexts where arr is not actually the array (but instead a pointer to the initial element). Other answers explain how this happens.

    I can thing of only one case: the array contains elements that are of different derived types of the type of the array.

    This cannot happen (for, fundamentally, the same reason that Java arrays don't play nicely with generics). The array is statically typed; it reserves "slots" of memory that are sized for a specific type (the base type).

    Sorry for the trivial question, I am a Java dev and I am rather new to C++.

    C++ arrays are not first-class objects. You can use boost::array to make them behave more like Java arrays, but keep in mind that you will still have value semantics rather than reference semantics, just like with everything else. (In particular, this means that you cannot really declare a variable of type analogous to Foo[] in Java, nor replace an array with another one of a different size; the array size is a part of the type.) Use .size() with this class where you would use .length in Java. (It also supplies iterators that provide the usual interface for C++ iterators.)

提交回复
热议问题