What is the best way to determine how many rows are in the array? |
Hopefully this is a DLL you can manage and modify the code to be less of a PITA badly written.
The function will work if:
1. the number of array elements are hard-coded into the function's code. Pass an array of different size and things will go bad, real bad, depending on if the array size is smaller or larger than expected.
2. you pass a pointer to the last element of the array.
3. the array contains a sentinel value at the end (the reason why a C string char array has '\0' as the last value.)
When using a regular array you really should also pass the size (number of rows/elements) into the function.
void Process(const double price[], int size)
Using a vector making passing one into a function much easier.
void Process(const std::vector<double>& price)
A vector keeps track of the number of elements it contains and can be accessed at any time with the
size()
method.
When using a multi-dimensional container vectors really shine. If you have a 2D vector:
void printMatrix(std::vector<std::vector<int>>& matrix)
and calling the function:
printMatrix(myMatrix); // function call
The C++ STL containers are designed to make a lot of the tedious book-keeping of regular containers less of a hassle.
zapshe wrote: |
---|
It'll know how many rows/columns are in the array when it's passed in.
|
No, it won't. A regular array has no inherent way of knowing what its size is, whether passed into a function or not.
std::vector
was coded to overcome this problem.