How can I find the number of elements in an array?

前端 未结 14 1147
广开言路
广开言路 2020-12-02 15:01

I have an int array and I need to find the number of elements in it. I know it has something to do with sizeof but I\'m not sure how to use it exac

相关标签:
14条回答
  • 2020-12-02 16:05

    If you have your array in scope you can use sizeof to determine its size in bytes and use the division to calculate the number of elements:

    #define NUM_OF_ELEMS 10
    int arr[NUM_OF_ELEMS];
    size_t NumberOfElements = sizeof(arr)/sizeof(arr[0]);
    

    If you receive an array as a function argument or allocate an array in heap you can not determine its size using the sizeof. You'll have to store/pass the size information somehow to be able to use it:

    void DoSomethingWithArray(int* arr, int NumOfElems)
    {
        for(int i = 0; i < NumOfElems; ++i) {
            arr[i] = /*...*/
        }
    }
    
    0 讨论(0)
  • 2020-12-02 16:05

    sizeof returns the size in bytes of it's argument. This is not what you want, but it can help.

    Let's say you have an array:

    int array[4];
    

    If you apply sizeof to the array (sizeof(array)), it will return its size in bytes, which in this case is 4 * the size of an int, so a total of maybe 16 bytes (depending on your implementation).

    If you apply sizeof to an element of the array (sizeof(array[0])), it will return its size in bytes, which in this case is the size of an int, so a total of maybe 4 bytes (depending on your implementation).

    If you divide the first one by the second one, it will be: (4 * the size of an int) / (the size of an int) = 4; That's exactly what you wanted.

    So this should do:

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

    Now you would probably like to have a macro to encapsulate this logic and never have to think again how it should be done:

    #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))
    

    You need the parentheses enclosing all the macro as in any other complex macro, and also enclosing every variable, just to avoid unexpected bugs related to operators precedence.

    Now you can use it on any array like this:

    int array[6];
    ptrdiff_t nmemb;
    
    nmemb = ARRAY_SIZE(array);
    /* nmemb == 6 */
    

    Remember that arguments of functions declared as arrays are not really arrays, but pointers to the first element of the array, so this will NOT work on them:

    void foo(int false_array[6])
    {
            ptrdiff_t nmemb;
    
            nmemb = ARRAY_SIZE(false_array);
            /* nmemb == sizeof(int *) / sizeof(int) */
            /* (maybe  ==2) */
    }
    

    But it can be used in functions if you pass a pointer to an array instead of just the array:

    void bar(int (*arrptr)[7])
    {
            ptrdiff_t nmemb;
    
            nmemb = ARRAY_SIZE(*arrptr);
            /* nmemb == 7 */
    }
    
    0 讨论(0)
提交回复
热议问题