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

前端 未结 14 1148
广开言路
广开言路 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 15:52
    #include<stdio.h>
    int main()
    {
        int arr[]={10,20,30,40,50,60};
        int *p;
        int count=0;
    
        for(p=arr;p<&arr+1;p++)
            count++;
    
        printf("The no of elements in array=%d",count);
    
        return 0;
    }
    

    OUTPUT=6

    EXPLANATION

    p is a pointer to a 1-D array, and in the loop for(p=arr,p<&arr+1;p++) I made p point to the base address. Suppose its base address is 1000; if we increment p then it points to 1002 and so on. Now coming to the concept of &arr - It basically represents the whole array, and if we add 1 to the whole array i.e. &arr+1, it gives the address 1012 i.e. the address of next 1-D array (in our case the size of int is 2), so the condition becomes 1000<1012.

    So, basically the condition becomes

    for(p=1000;p<1012;p++)
    

    And now let's check the condition and count the value

    • 1st time p=1000 and p<1012 condition is true: enter in the loop, increment the value of count to 1.
    • 2nd time p=1002 and p<1012 condition is true: enter in the loop, increment the value of count to 2.
    • ...
    • 6th time p=1010 and p<1012 condition is true: enter in the loop, increment the value of count to 6.
    • Last time p=1012 and p<1012 condition is false: print the value of count=6 in printf statement.
    0 讨论(0)
  • 2020-12-02 15:54

    Super easy.

    Just divide the number of allocated bytes by the number of bytes of the array's data type using sizeof().

    For example, given an integer array called myArray

    int numArrElements = sizeof(myArray) / sizeof(int);
    

    Now, if the data type of your array isn't constant and could possibly change, make the divisor in the equation use the size of the first value as the size of the data type

    For example:

    int numArrElements = sizeof(myArray) / sizeof(myArray[0]);
    
    0 讨论(0)
  • 2020-12-02 15:55

    It is not possible to find the number of elements in an array unless it is a character array. Consider the below example:

    int main()
    {
        int arr[100]={1,2,3,4,5};
        int size = sizeof(arr)/sizeof(arr[0]);
        printf("%d", size);
        return 1;
    }
    

    The above value gives us value 100 even if the number of elements is five. If it is a character array, you can search linearly for the null string at the end of the array and increase the counter as you go through.

    0 讨论(0)
  • 2020-12-02 15:59

    The question is simple: given a C++ array (e.g. x as in int x[10]), how would you get the number of elements in it?

    An obvious solution is the following macro (definition 1):

    #define countof( array ) ( sizeof( array )/sizeof( array[0] ) )
    

    I cannot say this isn’t correct, because it does give the right answer when you give it an array. However, the same expression gives you something bogus when you supply something that is not an array. For example, if you have

    int * p;
    

    then countof( p ) always give you 1 on a machine where an int pointer and an int have the same size (e.g. on a Win32 platform).

    This macro also wrongfully accepts any object of a class that has a member function operator[]. For example, suppose you write

    class IntArray {
    private:
        int * p;
        size_t size;
    public:
        int & operator [] ( size_t i );
    } x;
    

    then sizeof( x ) will be the size of the x object, not the size of the buffer pointed to by x.p. Therefore you won’t get a correct answer by countof( x ).

    So we conclude that definition 1 is not good because the compiler does not prevent you from misusing it. It fails to enforce that only an array can be passed in.

    What is a better option?

    Well, if we want the compiler to ensure that the parameter to countof is always an array, we have to find a context where only an array is allowed. The same context should reject any non-array expression.

    Some beginners may try this (definition 2):

    template <typename T, size_t N>
    size_t countof( T array[N] )
    {
       return N;
    }
    

    They figure, this template function will accept an array of N elements and return N.

    Unfortunately, this doesn’t compile because C++ treats an array parameter the same as a pointer parameter, i.e. the above definition is equivalent to:

    template <typename T, size_t N>
    size_t countof( T * array )
    {
        return N;
    }
    

    It now becomes obvious that the function body has no way of knowing what N is.

    However, if a function expects an array reference, then the compiler does make sure that the size of the actual parameter matches the declaration. This means we can make definition 2 work with a minor modification (definition 3):

    template <typename T, size_t N>
    size_t countof( T (&array)[N] )
    {
        return N;
    }
    

    This countof works very well and you cannot fool it by giving it a pointer. However, it is a function, not a macro. This means you cannot use it where a compile time constant is expected. In particular, you cannot write something like:

    int x[10];
    
    int y[ 2*countof(x) ]; // twice as big as x
    

    Can we do anything about it?

    Someone (I don’t know who it is – I just saw it in a piece of code from an unknown author) came up with a clever idea: moving N from the body of the function to the return type (e.g. make the function return an array of N elements), then we can get the value of N without actually calling the function.

    To be precise, we have to make the function return an array reference, as C++ does not allow you to return an array directly.

    The implementation of this is:

    template <typename T, size_t N>
    char ( &_ArraySizeHelper( T (&array)[N] ))[N];
    
    #define countof( array ) (sizeof( _ArraySizeHelper( array ) ))
    

    Admittedly, the syntax looks awful. Indeed, some explanation is necessary.

    First, the top-level stuff

    char ( &_ArraySizeHelper( ... ))[N];
    

    says _ArraySizeHelper is a function that returns a reference (note the &) to a char array of N elements.

    Next, the function parameter is

    T (&array)[N]
    

    which is a reference to a T array of N elements.

    Finally, countof is defined as the size of the result of the function _ArraySizeHelper. Note we don’t even need to define _ArraySizeHelper(), -- a declaration is enough.

    With this new definition,

    int x[10];
    
    int y[ 2*countof(x) ]; // twice as big as x
    

    becomes valid, just as we desire.

    Am I happy now? Well, I think this definition is definitely better than the others we have visited, but it is still not quite what I want. For one thing, it doesn’t work with types defined inside a function. That’s because the template function _ArraySizeHelper expects a type that is accessible in the global scope.

    I don’t have a better solution. If you know one, please let me know.

    0 讨论(0)
  • 2020-12-02 16:02
    int a[20];
    int length;
    length = sizeof(a) / sizeof(int);
    

    and you can use another way to make your code not be hard-coded to int

    Say if you have an array array

    you just need to:

    int len = sizeof(array) / sizeof(array[0]);
    
    0 讨论(0)
  • 2020-12-02 16:04

    Actually, there is no proper way to count the elements in a dynamic integer array. However, the sizeof command works properly in Linux, but it does not work properly in Windows. From a programmer's point of view, it is not recommended to use sizeof to take the number of elements in a dynamic array. We should keep track of the number of elements when making the array.

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