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

前端 未结 14 1235
广开言路
广开言路 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] = /*...*/
        }
    }
    

提交回复
热议问题