Is there a way to find how many values an array has? Detecting whether or not I\'ve reached the end of an array would also work.
Simply you can use this snippet:
#include <iostream>
#include <string>
#include <array>
using namespace std;
int main()
{
array<int,3> values;
cout << "No. elements in valuea array: " << values.size() << " elements." << endl;
cout << "sizeof(myints): " << sizeof(values) << endl;
}
and here is the reference : http://www.cplusplus.com/reference/array/array/size/
This is pretty much old and legendary question and there are already many amazing answers out there. But with time there are new functionalities being added to the languages, so we need to keep on updating things as per new features available.
I just noticed any one hasn't mentioned about C++20 yet. So thought to write answer.
In C++20, there is a new better way added to the standard library for finding the length of array i.e. std:ssize()
. This function returns a signed value
.
#include <iostream>
int main() {
int arr[] = {1, 2, 3};
std::cout << std::ssize(arr);
return 0;
}
In C++17 there was a better way (at that time) for the same which is std::size()
defined in iterator
.
#include <iostream>
#include <iterator> // required for std::size
int main(){
int arr[] = {1, 2, 3};
std::cout << "Size is " << std::size(arr);
return 0;
}
P.S. This method works for vector
as well.
This traditional approach is already mentioned in many other answers.
#include <iostream>
int main() {
int array[] = { 1, 2, 3 };
std::cout << sizeof(array) / sizeof(array[0]);
return 0;
}
Just FYI, if you wonder why this approach doesn't work when array is passed to another function. The reason is,
An array is not passed by value in C++, instead the pointer to array is passed. As in some cases passing the whole arrays can be expensive operation. You can test this by passing the array to some function and make some changes to array there and then print the array in main again. You'll get updated results.
And as you would already know, the sizeof()
function gives the number of bytes, so in other function it'll return the number of bytes allocated for the pointer rather than the whole array. So this approach doesn't work.
But I'm sure you can find a good way to do this, as per your requirement.
Happy Coding.
I provide a tricky solution here:
You can always store length
in the first element:
// malloc/new
arr[0] = length;
arr++;
// do anything.
int len = *(arr-1);
free(--arr);
The cost is you must --arr
when invoke free