Suppose that I have the following c
function:
int MyFunction( const float arr[] )
{
// define a variable to hold the number of items in 'arr'
int numItems = ...;
// do something here, then return...
return 1
}
How can I get into numItems
the number of items that are in the array arr
?
We can find the size of an array using the sizeof() operator as shown: // Finds size of arr[] and stores in 'size' int size = sizeof(arr)/sizeof(arr[0]);
We can get total number of elements in an array by using count() and sizeof() functions. Using count() Function: The count() function is used to get the total number of elements in an array.
The simple method to find the number of objects in an array is to take the size of the array divided by the size of one of its elements. Use the sizeof operator which returns the object's size in bytes.
Unfortunately you can't get it. In C, the following 2 are equivalent declarations.
int MyFunction( const float arr[] );
int MyFunction( const float* arr );
You must pass the size on your own.
int MyFunction( const float* arr, int nSize );
In case of char
pointers designating strings the length of the char array is determined by delimiter '\0'
.
Either you pass the number of elements in another argument or you have some convention on a delimiting element in the array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With