How do I find the length of an array?

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

    std::vector has a method size() which returns the number of elements in the vector.

    (Yes, this is tongue-in-cheek answer)

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

    Just a thought, but just decided to create a counter variable and store the array size in position [0]. I deleted most of the code I had in the function but you'll see after exiting the loop, prime[0] is assigned the final value of 'a'. I tried using vectors but VS Express 2013 didn't like that very much. Also make note that 'a' starts at one to avoid overwriting [0] and it's initialized in the beginning to avoid errors. I'm no expert, just thought I'd share.

    int prime[] = {0};
    int primes(int x, int y){
        using namespace std; int a = 1;
        for (int i = x; i <= y; i++){prime[a] = i; a++; }
        prime[0] = a; return 0;
    }
    
    0 讨论(0)
  • 2020-11-21 23:10

    Avoid using the type together with sizeof, as sizeof(array)/sizeof(char), suddenly gets corrupt if you change the type of the array.

    In visual studio, you have the equivivalent if sizeof(array)/sizeof(*array). You can simply type _countof(array)

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

    Lets say you have an global array declared at the top of the page

    int global[] = { 1, 2, 3, 4 };
    

    To find out how many elements are there (in c++) in the array type the following code:

    sizeof(global) / 4;
    

    The sizeof(NAME_OF_ARRAY) / 4 will give you back the number of elements for the given array name.

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

    While this is an old question, it's worth updating the answer to C++17. In the standard library there is now the templated function std::size(), which returns the number of elements in both a std container or a C-style array. For example:

    #include <iterator>
    
    uint32_t data[] = {10, 20, 30, 40};
    auto dataSize = std::size(data);
    // dataSize == 4
    
    0 讨论(0)
  • 2020-11-21 23:13

    you can find the length of an Array by following:

    int  arr[] = {1, 2, 3, 4, 5, 6}; 
    int size = *(&arr + 1) - arr; 
    cout << "Number of elements in arr[] is "<< size; 
    return 0;
    
    0 讨论(0)
提交回复
热议问题