首页 > 解决方案 > find number of element of array when it use as parameter in C++

问题描述

I write a function in c++ that should count number of elements an array has. function receive array as its parameter. so I try the following method:

int countArray(int a[])
{
    int size = 0;
    while(a[size] != NULL)
    {
        size++;
    }
    cout<<"number of array elements are : "<<size<<endl;
}

this function work but not perfectly. when i pass an array to this function which has same number of elements as its size int one[3] = {1,2,3} or an unsized array it will return result with one more element. for example for the previous array one[3] it will display number of array elements are 4.
but in other situation it work fine. for example if I pass an array that has less element than its size int two[4] = {1,2,3} it will work.
I should use array in this example not vector or struct , so what should i do or what is the reason that function doesn't work with that kind of array as its parameters.

标签: c++arrays

解决方案


Once an array have decayed to a pointer (to its first element), there's no way of getting its size.

The loop you have can (and most likely will) go out of bounds and you will have undefined behavior.

There are three possible solutions:

  1. Use std::array instead

  2. Use std::vector instead

  3. Use array-size deduction with templates:

    template<size_t N>
    int countArray(int (&a)[N]) { ... }
    

Also note that C++ doesn't have the concept of "null" values. The symbolic constant NULL is for pointers only.


推荐阅读