How do I find the length of an array?

前端 未结 27 2742
轮回少年
轮回少年 2020-11-21 23:10

Is there a way to find how many values an array has? Detecting whether or not I\'ve reached the end of an array would also work.

相关标签:
27条回答
  • 2020-11-21 23:15

    Here is one implementation of ArraySize from Google Protobuf.

    #define GOOGLE_ARRAYSIZE(a) \
      ((sizeof(a) / sizeof(*(a))) / static_cast<size_t>(!(sizeof(a) % sizeof(*(a)))))
    
    // test codes...
    char* ptr[] = { "you", "are", "here" };
    int testarr[] = {1, 2, 3, 4};
    cout << GOOGLE_ARRAYSIZE(testarr) << endl;
    cout << GOOGLE_ARRAYSIZE(ptr) << endl;
    

    ARRAYSIZE(arr) works by inspecting sizeof(arr) (the # of bytes in the array) and sizeof(*(arr)) (the # of bytes in one array element). If the former is divisible by the latter, perhaps arr is indeed an array, in which case the division result is the # of elements in the array. Otherwise, arr cannot possibly be an array, and we generate a compiler error to prevent the code from compiling.

    Since the size of bool is implementation-defined, we need to cast !(sizeof(a) & sizeof(*(a))) to size_t in order to ensure the final result has type size_t.

    This macro is not perfect as it wrongfully accepts certain pointers, namely where the pointer size is divisible by the pointee size. Since all our code has to go through a 32-bit compiler, where a pointer is 4 bytes, this means all pointers to a type whose size is 3 or greater than 4 will be (righteously) rejected.

    0 讨论(0)
  • 2020-11-21 23:19

    In C++, using the std::array class to declare an array, one can easily find the size of an array and also the last element.

    #include<iostream>
    #include<array>
    int main()
    {
        std::array<int,3> arr;
    
        //To find the size of the array
        std::cout<<arr.size()<<std::endl;
    
        //Accessing the last element
        auto it=arr.end();
        std::cout<<arr.back()<<"\t"<<arr[arr.size()-1]<<"\t"<<*(--it);
    
        return 0;
    }
    

    In fact, array class has a whole lot of other functions which let us use array a standard container.
    Reference 1 to C++ std::array class
    Reference 2 to std::array class
    The examples in the references are helpful.

    0 讨论(0)
  • 2020-11-21 23:19

    sizeof(array_name) gives the size of whole array and sizeof(int) gives the size of the data type of every array element.

    So dividing the size of the whole array by the size of a single element of the array gives the length of the array.

     int array_name[] = {1, 2, 3, 4, 5, 6};
     int length = sizeof(array_name)/sizeof(int);
    
    0 讨论(0)
  • 2020-11-21 23:22

    As other's said you can use the sizeof(arr)/sizeof(*arr) but this will give you the wrong answer for pointer types that aren't arrays.

    template<class T, size_t N>
    constexpr size_t size(T (&)[N]) { return N; }
    

    This has the nice property of failing to compile for non array types (visual studio has _countof which does this). The constexpr makes this a compile time expression so it doesn't have any drawbacks over the macro (at least none I know of).

    You can also consider using std::array from C++11 which exposes its length with no overhead over a native C array.

    C++17 has std::size() in the <iterator> header which does the same and works for STL containers too (thanks to @Jon C).

    0 讨论(0)
  • 2020-11-21 23:22

    ANSWER:

    int number_of_elements = sizeof(array)/sizeof(array[0])
    

    EXPLANATION:

    Since the compiler sets a specific size chunk of memory aside for each type of data, and an array is simply a group of those, you simply divide the size of the array by the size of the data type. If I have an array of 30 strings, my system sets aside 24 bytes for each element(string) of the array. At 30 elements, that's a total of 720 bytes. 720/24 == 30 elements. The small, tight algorithm for that is:

    int number_of_elements = sizeof(array)/sizeof(array[0]) which equates to

    number_of_elements = 720/24

    Note that you don't need to know what data type the array is, even if it's a custom data type.

    0 讨论(0)
  • 2020-11-21 23:24

    If you mean a C-style array, then you can do something like:

    int a[7];
    std::cout << "Length of array = " << (sizeof(a)/sizeof(*a)) << std::endl;
    

    This doesn't work on pointers (i.e. it won't work for either of the following):

    int *p = new int[7];
    std::cout << "Length of array = " << (sizeof(p)/sizeof(*p)) << std::endl;
    

    or:

    void func(int *p)
    {
        std::cout << "Length of array = " << (sizeof(p)/sizeof(*p)) << std::endl;
    }
    
    int a[7];
    func(a);
    

    In C++, if you want this kind of behavior, then you should be using a container class; probably std::vector.

    0 讨论(0)
提交回复
热议问题