How do I find the length of an array?

前端 未结 27 2866
轮回少年
轮回少年 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:25

    For old g++ compiler, you can do this

    template <class T, size_t N>
    char (&helper(T (&)[N]))[N];
    
    #define arraysize(array) (sizeof(helper(array)))
    
    int main() {
        int a[10];
        std::cout << arraysize(a) << std::endl;
        return 0;
    }
    
    0 讨论(0)
  • 2020-11-21 23:25

    I personally would suggest (if you are unable to work with specialized functions for whatever reason) to first expand the arrays type compatibility past what you would normally use it as (if you were storing values ≥ 0:

    unsigned int x[] -> int x[]
    

    than you would make the array 1 element bigger than you need to make it. For the last element you would put some type that is included in the expanded type specifier but that you wouldn't normally use e.g. using the previous example the last element would be -1. This enables you (by using a for loop) to find the last element of an array.

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

    Doing sizeof( myArray ) will get you the total number of bytes allocated for that array. You can then find out the number of elements in the array by dividing by the size of one element in the array: sizeof( myArray[0] )

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

    For C++/CX (when writing e.g. UWP apps using C++ in Visual Studio) we can find the number of values in an array by simply using the size() function.

    Source Code:

    string myArray[] = { "Example1", "Example2", "Example3", "Example4" };
    int size_of_array=size(myArray);
    

    If you cout the size_of_array the output will be:

    >>> 4
    
    0 讨论(0)
  • 2020-11-21 23:28

    A good solution that uses generics:

    template <typename T,unsigned S>
    inline unsigned arraysize(const T (&v)[S]) { return S; }
    

    Then simply call arraysize(_Array); to get the length of the array.

    Source

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

    Is there a way to find how many values an array has?

    Yes!

    Try sizeof(array)/sizeof(array[0])

    Detecting whether or not I've reached the end of an array would also work.

    I dont see any way for this unless your array is an array of characters (i.e string).

    P.S : In C++ always use std::vector. There are several inbuilt functions and an extended functionality.

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