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.
std::vector. The idiomatic way of working on containers in modern c++ is to pass ranges (pairs of iterators).a[size] != NULLdoes not check whether there's an element in the array at that indexNULLwithnullptr. If it does not compile then your are not doing it correctly.std::vector. Variable length arrays are not allowed in portable C++ either.