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.
If you mean a C-style array, then you can do something like:
int a[7];
std::cout << "Length of array = " << (sizeof(a)/sizeof(*a)) << std::endl;
This doesn't work on pointers (i.e. it won't work for either of the following):
int *p = new int[7];
std::cout << "Length of array = " << (sizeof(p)/sizeof(*p)) << std::endl;
or:
void func(int *p)
{
std::cout << "Length of array = " << (sizeof(p)/sizeof(*p)) << std::endl;
}
int a[7];
func(a);
In C++, if you want this kind of behavior, then you should be using a container class; probably std::vector.
As others have said, you can use the sizeof(arr)/sizeof(*arr), but this will give you the wrong answer for pointer types that aren't arrays.
template<class T, size_t N>
constexpr size_t size(T (&)[N]) { return N; }
This has the nice property of failing to compile for non-array types (Visual Studio has _countof which does this). The constexpr makes this a compile time expression so it doesn't have any drawbacks over the macro (at least none I know of).
You can also consider using std::array from C++11, which exposes its length with no overhead over a native C array.
C++17 has std::size() in the <iterator> header which does the same and works for STL containers too (thanks to #Jon C).
Doing sizeof myArray will get you the total number of bytes allocated for that array. You can then find out the number of elements in the array by dividing by the size of one element in the array: sizeof myArray[0]
So, you get something like:
size_t LengthOfArray = sizeof myArray / sizeof myArray[0];
Since sizeof yields a size_t, the result LengthOfArray will also be of this type.
While this is an old question, it's worth updating the answer to C++17. In the standard library there is now the templated function std::size(), which returns the number of elements in both a std container or a C-style array. For example:
#include <iterator>
uint32_t data[] = {10, 20, 30, 40};
auto dataSize = std::size(data);
// dataSize == 4
Is there a way to find how many values an array has?
Yes!
Try sizeof(array)/sizeof(array[0])
Detecting whether or not I've reached the end of an array would also work.
I dont see any way for this unless your array is an array of characters (i.e string).
P.S : In C++ always use std::vector. There are several inbuilt functions and an extended functionality.
#include <iostream>
int main ()
{
using namespace std;
int arr[] = {2, 7, 1, 111};
auto array_length = end(arr) - begin(arr);
cout << "Length of array: " << array_length << endl;
}
std::vector has a method size() which returns the number of elements in the vector.
(Yes, this is tongue-in-cheek answer)
Since C++11, some new templates are introduced to help reduce the pain when dealing with array length. All of them are defined in header <type_traits>.
std::rank<T>::value
If T is an array type, provides the member constant value equal to the number of dimensions of the array. For any other type, value is 0.
std::extent<T, N>::value
If T is an array type, provides the member constant value equal to the number of elements along the Nth dimension of the array, if N is in [0, std::rank<T>::value). For any other type, or if T is array of unknown bound along its first dimension and N is 0, value is 0.
std::remove_extent<T>::type
If T is an array of some type X, provides the member typedef type equal to X, otherwise type is T. Note that if T is a multidimensional array, only the first dimension is removed.
std::remove_all_extents<T>::type
If T is a multidimensional array of some type X, provides the member typedef type equal to X, otherwise type is T.
To get the length on any dimension of a multidimential array, decltype could be used to combine with std::extent. For example:
#include <iostream>
#include <type_traits> // std::remove_extent std::remove_all_extents std::rank std::extent
template<class T, size_t N>
constexpr size_t length(T(&)[N]) { return N; }
template<class T, size_t N>
constexpr size_t length2(T(&arr)[N]) { return sizeof(arr) / sizeof(*arr); }
int main()
{
int a[5][4][3]{{{1,2,3}, {4,5,6}}, { }, {{7,8,9}}};
// New way
constexpr auto l1 = std::extent<decltype(a)>::value; // 5
constexpr auto l2 = std::extent<decltype(a), 1>::value; // 4
constexpr auto l3 = std::extent<decltype(a), 2>::value; // 3
constexpr auto l4 = std::extent<decltype(a), 3>::value; // 0
// Mixed way
constexpr auto la = length(a);
//constexpr auto lpa = length(*a); // compile error
//auto lpa = length(*a); // get at runtime
std::remove_extent<decltype(a)>::type pa; // get at compile time
//std::remove_reference<decltype(*a)>::type pa; // same as above
constexpr auto lpa = length(pa);
std::cout << la << ' ' << lpa << '\n';
// Old way
constexpr auto la2 = sizeof(a) / sizeof(*a);
constexpr auto lpa2 = sizeof(*a) / sizeof(**a);
std::cout << la2 << ' ' << lpa2 << '\n';
return 0;
}
BTY, to get the total number of elements in a multidimentional array:
constexpr auto l = sizeof(a) / sizeof(std::remove_all_extents<decltype(a)>::type);
Or put it in a function template:
#include <iostream>
#include <type_traits>
template<class T>
constexpr size_t len(T &a)
{
return sizeof(a) / sizeof(typename std::remove_all_extents<T>::type);
}
int main()
{
int a[5][4][3]{{{1,2,3}, {4,5,6}}, { }, {{7,8,9}}};
constexpr auto ttt = len(a);
int i;
std::cout << ttt << ' ' << len(i) << '\n';
return 0;
}
More examples of how to use them could be found by following the links.
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.
C++20
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;
}
C++17
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.
Old
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.
There's also the TR1/C++11/C++17 way (see it Live on Coliru):
const std::string s[3] = { "1"s, "2"s, "3"s };
constexpr auto n = std::extent< decltype(s) >::value; // From <type_traits>
constexpr auto n2 = std::extent_v< decltype(s) >; // C++17 shorthand
const auto a = std::array{ "1"s, "2"s, "3"s }; // C++17 class template arg deduction -- http://en.cppreference.com/w/cpp/language/class_template_argument_deduction
constexpr auto size = std::tuple_size_v< decltype(a) >;
std::cout << n << " " << n2 << " " << size << "\n"; // Prints 3 3 3
Instead of using the built in array function aka:
int x[3] = {0, 1, 2};
you should use the array class and the array template. Try:
#include <array>
array<type_of_the_array, number_of_elements_in_the_array> Name_of_Array = {};
So now if you want to find the length of the array, all you have to do is using the size function in the array class.
Name_of_Array.size();
and that should return the length of elements in the array.
ANSWER:
int number_of_elements = sizeof(array)/sizeof(array[0])
EXPLANATION:
Since the compiler sets a specific size chunk of memory aside for each type of data, and an array is simply a group of those, you simply divide the size of the array by the size of the data type. If I have an array of 30 strings, my system sets aside 24 bytes for each element(string) of the array. At 30 elements, that's a total of 720 bytes. 720/24 == 30 elements. The small, tight algorithm for that is:
int number_of_elements = sizeof(array)/sizeof(array[0]) which equates to
number_of_elements = 720/24
Note that you don't need to know what data type the array is, even if it's a custom data type.
In C++, using the std::array class to declare an array, one can easily find the size of an array and also the last element.
#include<iostream>
#include<array>
int main()
{
std::array<int,3> arr;
//To find the size of the array
std::cout<<arr.size()<<std::endl;
//Accessing the last element
auto it=arr.end();
std::cout<<arr.back()<<"\t"<<arr[arr.size()-1]<<"\t"<<*(--it);
return 0;
}
In fact, array class has a whole lot of other functions which let us use array a standard container.
Reference 1 to C++ std::array class
Reference 2 to std::array class
The examples in the references are helpful.
You have a bunch of options to be used to get a C array size.
int myArray[] = {0, 1, 2, 3, 4, 5, 7};
1) sizeof(<array>) / sizeof(<type>):
std::cout << "Size:" << sizeof(myArray) / sizeof(int) << std::endl;
2) sizeof(<array>) / sizeof(*<array>):
std::cout << "Size:" << sizeof(myArray) / sizeof(*myArray) << std::endl;
3) sizeof(<array>) / sizeof(<array>[<element>]):
std::cout << "Size:" << sizeof(myArray) / sizeof(myArray[0]) << std::endl;
sizeof(array_name) gives the size of whole array and sizeof(int) gives the size of the data type of every array element.
So dividing the size of the whole array by the size of a single element of the array gives the length of the array.
int array_name[] = {1, 2, 3, 4, 5, 6};
int length = sizeof(array_name)/sizeof(int);
Here is one implementation of ArraySize from Google Protobuf.
#define GOOGLE_ARRAYSIZE(a) \
((sizeof(a) / sizeof(*(a))) / static_cast<size_t>(!(sizeof(a) % sizeof(*(a)))))
// test codes...
char* ptr[] = { "you", "are", "here" };
int testarr[] = {1, 2, 3, 4};
cout << GOOGLE_ARRAYSIZE(testarr) << endl;
cout << GOOGLE_ARRAYSIZE(ptr) << endl;
ARRAYSIZE(arr) works by inspecting sizeof(arr) (the # of bytes in
the array) and sizeof(*(arr)) (the # of bytes in one array
element). If the former is divisible by the latter, perhaps arr is
indeed an array, in which case the division result is the # of
elements in the array. Otherwise, arr cannot possibly be an array,
and we generate a compiler error to prevent the code from
compiling.
Since the size of bool is implementation-defined, we need to cast
!(sizeof(a) & sizeof(*(a))) to size_t in order to ensure the final
result has type size_t.
This macro is not perfect as it wrongfully accepts certain
pointers, namely where the pointer size is divisible by the pointee
size. Since all our code has to go through a 32-bit compiler,
where a pointer is 4 bytes, this means all pointers to a type whose
size is 3 or greater than 4 will be (righteously) rejected.
A good solution that uses generics:
template <typename T,unsigned S>
inline unsigned arraysize(const T (&v)[S]) { return S; }
Then simply call arraysize(_Array); to get the length of the array.
Source
For old g++ compiler, you can do this
template <class T, size_t N>
char (&helper(T (&)[N]))[N];
#define arraysize(array) (sizeof(helper(array)))
int main() {
int a[10];
std::cout << arraysize(a) << std::endl;
return 0;
}
For C++/CX (when writing e.g. UWP apps using C++ in Visual Studio) we can find the number of values in an array by simply using the size() function.
Source Code:
string myArray[] = { "Example1", "Example2", "Example3", "Example4" };
int size_of_array=size(myArray);
If you cout the size_of_array the output will be:
>>> 4
you can find the length of an Array by following:
int arr[] = {1, 2, 3, 4, 5, 6};
int size = *(&arr + 1) - arr;
cout << "Number of elements in arr[] is "<< size;
return 0;
Just a thought, but just decided to create a counter variable and store the array size in position [0]. I deleted most of the code I had in the function but you'll see after exiting the loop, prime[0] is assigned the final value of 'a'. I tried using vectors but VS Express 2013 didn't like that very much. Also make note that 'a' starts at one to avoid overwriting [0] and it's initialized in the beginning to avoid errors. I'm no expert, just thought I'd share.
int prime[] = {0};
int primes(int x, int y){
using namespace std; int a = 1;
for (int i = x; i <= y; i++){prime[a] = i; a++; }
prime[0] = a; return 0;
}
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/
You can use the sizeof() operator which is used for the same purpose.
see below the sample code
#include <iostream>
using namespace std;
int main() {
int arr[] = {10,20,30,40,50,60};
int arrSize = sizeof(arr)/sizeof(arr[0]);
cout << "The size of the array is: " << arrSize;
return 0;
}
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
Avoid using the type together with sizeof, as sizeof(array)/sizeof(char), suddenly gets corrupt if you change the type of the array.
In visual studio, you have the equivivalent if sizeof(array)/sizeof(*array).
You can simply type _countof(array)
One of the most common reasons you would end up looking for this is because you want to pass an array to a function, and not have to pass another argument for its size. You would also generally like the array size to be dynamic. That array might contain objects, not primitives, and the objects maybe complex such that size_of() is a not safe option for calculating the count.
As others have suggested, consider using an std::vector or list, etc in instead of a primitive array. On old compilers, however, you still wouldn't have the final solution you probably want by doing simply that though, because populating the container requires a bunch of ugly push_back() lines. If you're like me, want a single line solution with anonymous objects involved.
If you go with STL container alternative to a primitive array, this SO post may be of use to you for ways to initialize it:
What is the easiest way to initialize a std::vector with hardcoded elements?
Here's a method that I'm using for this which will work universally across compilers and platforms:
Create a struct or class as container for your collection of objects. Define an operator overload function for <<.
class MyObject;
struct MyObjectList
{
std::list<MyObject> objects;
MyObjectList& operator<<( const MyObject o )
{
objects.push_back( o );
return *this;
}
};
You can create functions which take your struct as a parameter, e.g.:
someFunc( MyObjectList &objects );
Then, you can call that function, like this:
someFunc( MyObjectList() << MyObject(1) << MyObject(2) << MyObject(3) );
That way, you can build and pass a dynamically sized collection of objects to a function in one single clean line!
I personally would suggest (if you are unable to work with specialized functions for whatever reason) to first expand the arrays type compatibility past what you would normally use it as (if you were storing values ≥ 0:
unsigned int x[] -> int x[]
than you would make the array 1 element bigger than you need to make it. For the last element you would put some type that is included in the expanded type specifier but that you wouldn't normally use e.g. using the previous example the last element would be -1. This enables you (by using a for loop) to find the last element of an array.
here you go:
#include <iostream>
using namespace std;
int main() {
int arr[] = {10,20,30,40,50,60};
int arrSize = sizeof(arr)/sizeof(arr[0]);
cout << "The size of the array is: " << arrSize;
return 0;
}
I think this will work:
for(int i=0;array[i];i++)
{
//do_something
}
Lets say you have an global array declared at the top of the page
int global[] = { 1, 2, 3, 4 };
To find out how many elements are there (in c++) in the array type the following code:
sizeof(global) / 4;
The sizeof(NAME_OF_ARRAY) / 4 will give you back the number of elements for the given array name.
Related
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.
If you mean a C-style array, then you can do something like:
int a[7];
std::cout << "Length of array = " << (sizeof(a)/sizeof(*a)) << std::endl;
This doesn't work on pointers (i.e. it won't work for either of the following):
int *p = new int[7];
std::cout << "Length of array = " << (sizeof(p)/sizeof(*p)) << std::endl;
or:
void func(int *p)
{
std::cout << "Length of array = " << (sizeof(p)/sizeof(*p)) << std::endl;
}
int a[7];
func(a);
In C++, if you want this kind of behavior, then you should be using a container class; probably std::vector.
As others have said, you can use the sizeof(arr)/sizeof(*arr), but this will give you the wrong answer for pointer types that aren't arrays.
template<class T, size_t N>
constexpr size_t size(T (&)[N]) { return N; }
This has the nice property of failing to compile for non-array types (Visual Studio has _countof which does this). The constexpr makes this a compile time expression so it doesn't have any drawbacks over the macro (at least none I know of).
You can also consider using std::array from C++11, which exposes its length with no overhead over a native C array.
C++17 has std::size() in the <iterator> header which does the same and works for STL containers too (thanks to #Jon C).
Doing sizeof myArray will get you the total number of bytes allocated for that array. You can then find out the number of elements in the array by dividing by the size of one element in the array: sizeof myArray[0]
So, you get something like:
size_t LengthOfArray = sizeof myArray / sizeof myArray[0];
Since sizeof yields a size_t, the result LengthOfArray will also be of this type.
While this is an old question, it's worth updating the answer to C++17. In the standard library there is now the templated function std::size(), which returns the number of elements in both a std container or a C-style array. For example:
#include <iterator>
uint32_t data[] = {10, 20, 30, 40};
auto dataSize = std::size(data);
// dataSize == 4
Is there a way to find how many values an array has?
Yes!
Try sizeof(array)/sizeof(array[0])
Detecting whether or not I've reached the end of an array would also work.
I dont see any way for this unless your array is an array of characters (i.e string).
P.S : In C++ always use std::vector. There are several inbuilt functions and an extended functionality.
#include <iostream>
int main ()
{
using namespace std;
int arr[] = {2, 7, 1, 111};
auto array_length = end(arr) - begin(arr);
cout << "Length of array: " << array_length << endl;
}
std::vector has a method size() which returns the number of elements in the vector.
(Yes, this is tongue-in-cheek answer)
Since C++11, some new templates are introduced to help reduce the pain when dealing with array length. All of them are defined in header <type_traits>.
std::rank<T>::value
If T is an array type, provides the member constant value equal to the number of dimensions of the array. For any other type, value is 0.
std::extent<T, N>::value
If T is an array type, provides the member constant value equal to the number of elements along the Nth dimension of the array, if N is in [0, std::rank<T>::value). For any other type, or if T is array of unknown bound along its first dimension and N is 0, value is 0.
std::remove_extent<T>::type
If T is an array of some type X, provides the member typedef type equal to X, otherwise type is T. Note that if T is a multidimensional array, only the first dimension is removed.
std::remove_all_extents<T>::type
If T is a multidimensional array of some type X, provides the member typedef type equal to X, otherwise type is T.
To get the length on any dimension of a multidimential array, decltype could be used to combine with std::extent. For example:
#include <iostream>
#include <type_traits> // std::remove_extent std::remove_all_extents std::rank std::extent
template<class T, size_t N>
constexpr size_t length(T(&)[N]) { return N; }
template<class T, size_t N>
constexpr size_t length2(T(&arr)[N]) { return sizeof(arr) / sizeof(*arr); }
int main()
{
int a[5][4][3]{{{1,2,3}, {4,5,6}}, { }, {{7,8,9}}};
// New way
constexpr auto l1 = std::extent<decltype(a)>::value; // 5
constexpr auto l2 = std::extent<decltype(a), 1>::value; // 4
constexpr auto l3 = std::extent<decltype(a), 2>::value; // 3
constexpr auto l4 = std::extent<decltype(a), 3>::value; // 0
// Mixed way
constexpr auto la = length(a);
//constexpr auto lpa = length(*a); // compile error
//auto lpa = length(*a); // get at runtime
std::remove_extent<decltype(a)>::type pa; // get at compile time
//std::remove_reference<decltype(*a)>::type pa; // same as above
constexpr auto lpa = length(pa);
std::cout << la << ' ' << lpa << '\n';
// Old way
constexpr auto la2 = sizeof(a) / sizeof(*a);
constexpr auto lpa2 = sizeof(*a) / sizeof(**a);
std::cout << la2 << ' ' << lpa2 << '\n';
return 0;
}
BTY, to get the total number of elements in a multidimentional array:
constexpr auto l = sizeof(a) / sizeof(std::remove_all_extents<decltype(a)>::type);
Or put it in a function template:
#include <iostream>
#include <type_traits>
template<class T>
constexpr size_t len(T &a)
{
return sizeof(a) / sizeof(typename std::remove_all_extents<T>::type);
}
int main()
{
int a[5][4][3]{{{1,2,3}, {4,5,6}}, { }, {{7,8,9}}};
constexpr auto ttt = len(a);
int i;
std::cout << ttt << ' ' << len(i) << '\n';
return 0;
}
More examples of how to use them could be found by following the links.
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.
C++20
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;
}
C++17
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.
Old
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.
There's also the TR1/C++11/C++17 way (see it Live on Coliru):
const std::string s[3] = { "1"s, "2"s, "3"s };
constexpr auto n = std::extent< decltype(s) >::value; // From <type_traits>
constexpr auto n2 = std::extent_v< decltype(s) >; // C++17 shorthand
const auto a = std::array{ "1"s, "2"s, "3"s }; // C++17 class template arg deduction -- http://en.cppreference.com/w/cpp/language/class_template_argument_deduction
constexpr auto size = std::tuple_size_v< decltype(a) >;
std::cout << n << " " << n2 << " " << size << "\n"; // Prints 3 3 3
Instead of using the built in array function aka:
int x[3] = {0, 1, 2};
you should use the array class and the array template. Try:
#include <array>
array<type_of_the_array, number_of_elements_in_the_array> Name_of_Array = {};
So now if you want to find the length of the array, all you have to do is using the size function in the array class.
Name_of_Array.size();
and that should return the length of elements in the array.
ANSWER:
int number_of_elements = sizeof(array)/sizeof(array[0])
EXPLANATION:
Since the compiler sets a specific size chunk of memory aside for each type of data, and an array is simply a group of those, you simply divide the size of the array by the size of the data type. If I have an array of 30 strings, my system sets aside 24 bytes for each element(string) of the array. At 30 elements, that's a total of 720 bytes. 720/24 == 30 elements. The small, tight algorithm for that is:
int number_of_elements = sizeof(array)/sizeof(array[0]) which equates to
number_of_elements = 720/24
Note that you don't need to know what data type the array is, even if it's a custom data type.
In C++, using the std::array class to declare an array, one can easily find the size of an array and also the last element.
#include<iostream>
#include<array>
int main()
{
std::array<int,3> arr;
//To find the size of the array
std::cout<<arr.size()<<std::endl;
//Accessing the last element
auto it=arr.end();
std::cout<<arr.back()<<"\t"<<arr[arr.size()-1]<<"\t"<<*(--it);
return 0;
}
In fact, array class has a whole lot of other functions which let us use array a standard container.
Reference 1 to C++ std::array class
Reference 2 to std::array class
The examples in the references are helpful.
You have a bunch of options to be used to get a C array size.
int myArray[] = {0, 1, 2, 3, 4, 5, 7};
1) sizeof(<array>) / sizeof(<type>):
std::cout << "Size:" << sizeof(myArray) / sizeof(int) << std::endl;
2) sizeof(<array>) / sizeof(*<array>):
std::cout << "Size:" << sizeof(myArray) / sizeof(*myArray) << std::endl;
3) sizeof(<array>) / sizeof(<array>[<element>]):
std::cout << "Size:" << sizeof(myArray) / sizeof(myArray[0]) << std::endl;
sizeof(array_name) gives the size of whole array and sizeof(int) gives the size of the data type of every array element.
So dividing the size of the whole array by the size of a single element of the array gives the length of the array.
int array_name[] = {1, 2, 3, 4, 5, 6};
int length = sizeof(array_name)/sizeof(int);
Here is one implementation of ArraySize from Google Protobuf.
#define GOOGLE_ARRAYSIZE(a) \
((sizeof(a) / sizeof(*(a))) / static_cast<size_t>(!(sizeof(a) % sizeof(*(a)))))
// test codes...
char* ptr[] = { "you", "are", "here" };
int testarr[] = {1, 2, 3, 4};
cout << GOOGLE_ARRAYSIZE(testarr) << endl;
cout << GOOGLE_ARRAYSIZE(ptr) << endl;
ARRAYSIZE(arr) works by inspecting sizeof(arr) (the # of bytes in
the array) and sizeof(*(arr)) (the # of bytes in one array
element). If the former is divisible by the latter, perhaps arr is
indeed an array, in which case the division result is the # of
elements in the array. Otherwise, arr cannot possibly be an array,
and we generate a compiler error to prevent the code from
compiling.
Since the size of bool is implementation-defined, we need to cast
!(sizeof(a) & sizeof(*(a))) to size_t in order to ensure the final
result has type size_t.
This macro is not perfect as it wrongfully accepts certain
pointers, namely where the pointer size is divisible by the pointee
size. Since all our code has to go through a 32-bit compiler,
where a pointer is 4 bytes, this means all pointers to a type whose
size is 3 or greater than 4 will be (righteously) rejected.
A good solution that uses generics:
template <typename T,unsigned S>
inline unsigned arraysize(const T (&v)[S]) { return S; }
Then simply call arraysize(_Array); to get the length of the array.
Source
For old g++ compiler, you can do this
template <class T, size_t N>
char (&helper(T (&)[N]))[N];
#define arraysize(array) (sizeof(helper(array)))
int main() {
int a[10];
std::cout << arraysize(a) << std::endl;
return 0;
}
For C++/CX (when writing e.g. UWP apps using C++ in Visual Studio) we can find the number of values in an array by simply using the size() function.
Source Code:
string myArray[] = { "Example1", "Example2", "Example3", "Example4" };
int size_of_array=size(myArray);
If you cout the size_of_array the output will be:
>>> 4
you can find the length of an Array by following:
int arr[] = {1, 2, 3, 4, 5, 6};
int size = *(&arr + 1) - arr;
cout << "Number of elements in arr[] is "<< size;
return 0;
Just a thought, but just decided to create a counter variable and store the array size in position [0]. I deleted most of the code I had in the function but you'll see after exiting the loop, prime[0] is assigned the final value of 'a'. I tried using vectors but VS Express 2013 didn't like that very much. Also make note that 'a' starts at one to avoid overwriting [0] and it's initialized in the beginning to avoid errors. I'm no expert, just thought I'd share.
int prime[] = {0};
int primes(int x, int y){
using namespace std; int a = 1;
for (int i = x; i <= y; i++){prime[a] = i; a++; }
prime[0] = a; return 0;
}
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/
You can use the sizeof() operator which is used for the same purpose.
see below the sample code
#include <iostream>
using namespace std;
int main() {
int arr[] = {10,20,30,40,50,60};
int arrSize = sizeof(arr)/sizeof(arr[0]);
cout << "The size of the array is: " << arrSize;
return 0;
}
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
Avoid using the type together with sizeof, as sizeof(array)/sizeof(char), suddenly gets corrupt if you change the type of the array.
In visual studio, you have the equivivalent if sizeof(array)/sizeof(*array).
You can simply type _countof(array)
One of the most common reasons you would end up looking for this is because you want to pass an array to a function, and not have to pass another argument for its size. You would also generally like the array size to be dynamic. That array might contain objects, not primitives, and the objects maybe complex such that size_of() is a not safe option for calculating the count.
As others have suggested, consider using an std::vector or list, etc in instead of a primitive array. On old compilers, however, you still wouldn't have the final solution you probably want by doing simply that though, because populating the container requires a bunch of ugly push_back() lines. If you're like me, want a single line solution with anonymous objects involved.
If you go with STL container alternative to a primitive array, this SO post may be of use to you for ways to initialize it:
What is the easiest way to initialize a std::vector with hardcoded elements?
Here's a method that I'm using for this which will work universally across compilers and platforms:
Create a struct or class as container for your collection of objects. Define an operator overload function for <<.
class MyObject;
struct MyObjectList
{
std::list<MyObject> objects;
MyObjectList& operator<<( const MyObject o )
{
objects.push_back( o );
return *this;
}
};
You can create functions which take your struct as a parameter, e.g.:
someFunc( MyObjectList &objects );
Then, you can call that function, like this:
someFunc( MyObjectList() << MyObject(1) << MyObject(2) << MyObject(3) );
That way, you can build and pass a dynamically sized collection of objects to a function in one single clean line!
I personally would suggest (if you are unable to work with specialized functions for whatever reason) to first expand the arrays type compatibility past what you would normally use it as (if you were storing values ≥ 0:
unsigned int x[] -> int x[]
than you would make the array 1 element bigger than you need to make it. For the last element you would put some type that is included in the expanded type specifier but that you wouldn't normally use e.g. using the previous example the last element would be -1. This enables you (by using a for loop) to find the last element of an array.
here you go:
#include <iostream>
using namespace std;
int main() {
int arr[] = {10,20,30,40,50,60};
int arrSize = sizeof(arr)/sizeof(arr[0]);
cout << "The size of the array is: " << arrSize;
return 0;
}
I think this will work:
for(int i=0;array[i];i++)
{
//do_something
}
Lets say you have an global array declared at the top of the page
int global[] = { 1, 2, 3, 4 };
To find out how many elements are there (in c++) in the array type the following code:
sizeof(global) / 4;
The sizeof(NAME_OF_ARRAY) / 4 will give you back the number of elements for the given array name.
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.
If you mean a C-style array, then you can do something like:
int a[7];
std::cout << "Length of array = " << (sizeof(a)/sizeof(*a)) << std::endl;
This doesn't work on pointers (i.e. it won't work for either of the following):
int *p = new int[7];
std::cout << "Length of array = " << (sizeof(p)/sizeof(*p)) << std::endl;
or:
void func(int *p)
{
std::cout << "Length of array = " << (sizeof(p)/sizeof(*p)) << std::endl;
}
int a[7];
func(a);
In C++, if you want this kind of behavior, then you should be using a container class; probably std::vector.
As others have said, you can use the sizeof(arr)/sizeof(*arr), but this will give you the wrong answer for pointer types that aren't arrays.
template<class T, size_t N>
constexpr size_t size(T (&)[N]) { return N; }
This has the nice property of failing to compile for non-array types (Visual Studio has _countof which does this). The constexpr makes this a compile time expression so it doesn't have any drawbacks over the macro (at least none I know of).
You can also consider using std::array from C++11, which exposes its length with no overhead over a native C array.
C++17 has std::size() in the <iterator> header which does the same and works for STL containers too (thanks to #Jon C).
Doing sizeof myArray will get you the total number of bytes allocated for that array. You can then find out the number of elements in the array by dividing by the size of one element in the array: sizeof myArray[0]
So, you get something like:
size_t LengthOfArray = sizeof myArray / sizeof myArray[0];
Since sizeof yields a size_t, the result LengthOfArray will also be of this type.
While this is an old question, it's worth updating the answer to C++17. In the standard library there is now the templated function std::size(), which returns the number of elements in both a std container or a C-style array. For example:
#include <iterator>
uint32_t data[] = {10, 20, 30, 40};
auto dataSize = std::size(data);
// dataSize == 4
Is there a way to find how many values an array has?
Yes!
Try sizeof(array)/sizeof(array[0])
Detecting whether or not I've reached the end of an array would also work.
I dont see any way for this unless your array is an array of characters (i.e string).
P.S : In C++ always use std::vector. There are several inbuilt functions and an extended functionality.
#include <iostream>
int main ()
{
using namespace std;
int arr[] = {2, 7, 1, 111};
auto array_length = end(arr) - begin(arr);
cout << "Length of array: " << array_length << endl;
}
std::vector has a method size() which returns the number of elements in the vector.
(Yes, this is tongue-in-cheek answer)
Since C++11, some new templates are introduced to help reduce the pain when dealing with array length. All of them are defined in header <type_traits>.
std::rank<T>::value
If T is an array type, provides the member constant value equal to the number of dimensions of the array. For any other type, value is 0.
std::extent<T, N>::value
If T is an array type, provides the member constant value equal to the number of elements along the Nth dimension of the array, if N is in [0, std::rank<T>::value). For any other type, or if T is array of unknown bound along its first dimension and N is 0, value is 0.
std::remove_extent<T>::type
If T is an array of some type X, provides the member typedef type equal to X, otherwise type is T. Note that if T is a multidimensional array, only the first dimension is removed.
std::remove_all_extents<T>::type
If T is a multidimensional array of some type X, provides the member typedef type equal to X, otherwise type is T.
To get the length on any dimension of a multidimential array, decltype could be used to combine with std::extent. For example:
#include <iostream>
#include <type_traits> // std::remove_extent std::remove_all_extents std::rank std::extent
template<class T, size_t N>
constexpr size_t length(T(&)[N]) { return N; }
template<class T, size_t N>
constexpr size_t length2(T(&arr)[N]) { return sizeof(arr) / sizeof(*arr); }
int main()
{
int a[5][4][3]{{{1,2,3}, {4,5,6}}, { }, {{7,8,9}}};
// New way
constexpr auto l1 = std::extent<decltype(a)>::value; // 5
constexpr auto l2 = std::extent<decltype(a), 1>::value; // 4
constexpr auto l3 = std::extent<decltype(a), 2>::value; // 3
constexpr auto l4 = std::extent<decltype(a), 3>::value; // 0
// Mixed way
constexpr auto la = length(a);
//constexpr auto lpa = length(*a); // compile error
//auto lpa = length(*a); // get at runtime
std::remove_extent<decltype(a)>::type pa; // get at compile time
//std::remove_reference<decltype(*a)>::type pa; // same as above
constexpr auto lpa = length(pa);
std::cout << la << ' ' << lpa << '\n';
// Old way
constexpr auto la2 = sizeof(a) / sizeof(*a);
constexpr auto lpa2 = sizeof(*a) / sizeof(**a);
std::cout << la2 << ' ' << lpa2 << '\n';
return 0;
}
BTY, to get the total number of elements in a multidimentional array:
constexpr auto l = sizeof(a) / sizeof(std::remove_all_extents<decltype(a)>::type);
Or put it in a function template:
#include <iostream>
#include <type_traits>
template<class T>
constexpr size_t len(T &a)
{
return sizeof(a) / sizeof(typename std::remove_all_extents<T>::type);
}
int main()
{
int a[5][4][3]{{{1,2,3}, {4,5,6}}, { }, {{7,8,9}}};
constexpr auto ttt = len(a);
int i;
std::cout << ttt << ' ' << len(i) << '\n';
return 0;
}
More examples of how to use them could be found by following the links.
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.
C++20
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;
}
C++17
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.
Old
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.
There's also the TR1/C++11/C++17 way (see it Live on Coliru):
const std::string s[3] = { "1"s, "2"s, "3"s };
constexpr auto n = std::extent< decltype(s) >::value; // From <type_traits>
constexpr auto n2 = std::extent_v< decltype(s) >; // C++17 shorthand
const auto a = std::array{ "1"s, "2"s, "3"s }; // C++17 class template arg deduction -- http://en.cppreference.com/w/cpp/language/class_template_argument_deduction
constexpr auto size = std::tuple_size_v< decltype(a) >;
std::cout << n << " " << n2 << " " << size << "\n"; // Prints 3 3 3
Instead of using the built in array function aka:
int x[3] = {0, 1, 2};
you should use the array class and the array template. Try:
#include <array>
array<type_of_the_array, number_of_elements_in_the_array> Name_of_Array = {};
So now if you want to find the length of the array, all you have to do is using the size function in the array class.
Name_of_Array.size();
and that should return the length of elements in the array.
ANSWER:
int number_of_elements = sizeof(array)/sizeof(array[0])
EXPLANATION:
Since the compiler sets a specific size chunk of memory aside for each type of data, and an array is simply a group of those, you simply divide the size of the array by the size of the data type. If I have an array of 30 strings, my system sets aside 24 bytes for each element(string) of the array. At 30 elements, that's a total of 720 bytes. 720/24 == 30 elements. The small, tight algorithm for that is:
int number_of_elements = sizeof(array)/sizeof(array[0]) which equates to
number_of_elements = 720/24
Note that you don't need to know what data type the array is, even if it's a custom data type.
In C++, using the std::array class to declare an array, one can easily find the size of an array and also the last element.
#include<iostream>
#include<array>
int main()
{
std::array<int,3> arr;
//To find the size of the array
std::cout<<arr.size()<<std::endl;
//Accessing the last element
auto it=arr.end();
std::cout<<arr.back()<<"\t"<<arr[arr.size()-1]<<"\t"<<*(--it);
return 0;
}
In fact, array class has a whole lot of other functions which let us use array a standard container.
Reference 1 to C++ std::array class
Reference 2 to std::array class
The examples in the references are helpful.
You have a bunch of options to be used to get a C array size.
int myArray[] = {0, 1, 2, 3, 4, 5, 7};
1) sizeof(<array>) / sizeof(<type>):
std::cout << "Size:" << sizeof(myArray) / sizeof(int) << std::endl;
2) sizeof(<array>) / sizeof(*<array>):
std::cout << "Size:" << sizeof(myArray) / sizeof(*myArray) << std::endl;
3) sizeof(<array>) / sizeof(<array>[<element>]):
std::cout << "Size:" << sizeof(myArray) / sizeof(myArray[0]) << std::endl;
sizeof(array_name) gives the size of whole array and sizeof(int) gives the size of the data type of every array element.
So dividing the size of the whole array by the size of a single element of the array gives the length of the array.
int array_name[] = {1, 2, 3, 4, 5, 6};
int length = sizeof(array_name)/sizeof(int);
Here is one implementation of ArraySize from Google Protobuf.
#define GOOGLE_ARRAYSIZE(a) \
((sizeof(a) / sizeof(*(a))) / static_cast<size_t>(!(sizeof(a) % sizeof(*(a)))))
// test codes...
char* ptr[] = { "you", "are", "here" };
int testarr[] = {1, 2, 3, 4};
cout << GOOGLE_ARRAYSIZE(testarr) << endl;
cout << GOOGLE_ARRAYSIZE(ptr) << endl;
ARRAYSIZE(arr) works by inspecting sizeof(arr) (the # of bytes in
the array) and sizeof(*(arr)) (the # of bytes in one array
element). If the former is divisible by the latter, perhaps arr is
indeed an array, in which case the division result is the # of
elements in the array. Otherwise, arr cannot possibly be an array,
and we generate a compiler error to prevent the code from
compiling.
Since the size of bool is implementation-defined, we need to cast
!(sizeof(a) & sizeof(*(a))) to size_t in order to ensure the final
result has type size_t.
This macro is not perfect as it wrongfully accepts certain
pointers, namely where the pointer size is divisible by the pointee
size. Since all our code has to go through a 32-bit compiler,
where a pointer is 4 bytes, this means all pointers to a type whose
size is 3 or greater than 4 will be (righteously) rejected.
A good solution that uses generics:
template <typename T,unsigned S>
inline unsigned arraysize(const T (&v)[S]) { return S; }
Then simply call arraysize(_Array); to get the length of the array.
Source
For old g++ compiler, you can do this
template <class T, size_t N>
char (&helper(T (&)[N]))[N];
#define arraysize(array) (sizeof(helper(array)))
int main() {
int a[10];
std::cout << arraysize(a) << std::endl;
return 0;
}
For C++/CX (when writing e.g. UWP apps using C++ in Visual Studio) we can find the number of values in an array by simply using the size() function.
Source Code:
string myArray[] = { "Example1", "Example2", "Example3", "Example4" };
int size_of_array=size(myArray);
If you cout the size_of_array the output will be:
>>> 4
you can find the length of an Array by following:
int arr[] = {1, 2, 3, 4, 5, 6};
int size = *(&arr + 1) - arr;
cout << "Number of elements in arr[] is "<< size;
return 0;
Just a thought, but just decided to create a counter variable and store the array size in position [0]. I deleted most of the code I had in the function but you'll see after exiting the loop, prime[0] is assigned the final value of 'a'. I tried using vectors but VS Express 2013 didn't like that very much. Also make note that 'a' starts at one to avoid overwriting [0] and it's initialized in the beginning to avoid errors. I'm no expert, just thought I'd share.
int prime[] = {0};
int primes(int x, int y){
using namespace std; int a = 1;
for (int i = x; i <= y; i++){prime[a] = i; a++; }
prime[0] = a; return 0;
}
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/
You can use the sizeof() operator which is used for the same purpose.
see below the sample code
#include <iostream>
using namespace std;
int main() {
int arr[] = {10,20,30,40,50,60};
int arrSize = sizeof(arr)/sizeof(arr[0]);
cout << "The size of the array is: " << arrSize;
return 0;
}
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
Avoid using the type together with sizeof, as sizeof(array)/sizeof(char), suddenly gets corrupt if you change the type of the array.
In visual studio, you have the equivivalent if sizeof(array)/sizeof(*array).
You can simply type _countof(array)
One of the most common reasons you would end up looking for this is because you want to pass an array to a function, and not have to pass another argument for its size. You would also generally like the array size to be dynamic. That array might contain objects, not primitives, and the objects maybe complex such that size_of() is a not safe option for calculating the count.
As others have suggested, consider using an std::vector or list, etc in instead of a primitive array. On old compilers, however, you still wouldn't have the final solution you probably want by doing simply that though, because populating the container requires a bunch of ugly push_back() lines. If you're like me, want a single line solution with anonymous objects involved.
If you go with STL container alternative to a primitive array, this SO post may be of use to you for ways to initialize it:
What is the easiest way to initialize a std::vector with hardcoded elements?
Here's a method that I'm using for this which will work universally across compilers and platforms:
Create a struct or class as container for your collection of objects. Define an operator overload function for <<.
class MyObject;
struct MyObjectList
{
std::list<MyObject> objects;
MyObjectList& operator<<( const MyObject o )
{
objects.push_back( o );
return *this;
}
};
You can create functions which take your struct as a parameter, e.g.:
someFunc( MyObjectList &objects );
Then, you can call that function, like this:
someFunc( MyObjectList() << MyObject(1) << MyObject(2) << MyObject(3) );
That way, you can build and pass a dynamically sized collection of objects to a function in one single clean line!
I personally would suggest (if you are unable to work with specialized functions for whatever reason) to first expand the arrays type compatibility past what you would normally use it as (if you were storing values ≥ 0:
unsigned int x[] -> int x[]
than you would make the array 1 element bigger than you need to make it. For the last element you would put some type that is included in the expanded type specifier but that you wouldn't normally use e.g. using the previous example the last element would be -1. This enables you (by using a for loop) to find the last element of an array.
here you go:
#include <iostream>
using namespace std;
int main() {
int arr[] = {10,20,30,40,50,60};
int arrSize = sizeof(arr)/sizeof(arr[0]);
cout << "The size of the array is: " << arrSize;
return 0;
}
I think this will work:
for(int i=0;array[i];i++)
{
//do_something
}
Lets say you have an global array declared at the top of the page
int global[] = { 1, 2, 3, 4 };
To find out how many elements are there (in c++) in the array type the following code:
sizeof(global) / 4;
The sizeof(NAME_OF_ARRAY) / 4 will give you back the number of elements for the given array name.
I'm learning about pointers and I can't get this code to work. Here's what I have so far:
void incrementArray(int* a[]) {
for(auto& x : a) {
++x;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int array[] = {0,1,2,3,4,5,6,7,8,9};
for(auto x : array) {
cout << x << '\n';
}
incrementArray(&array);
for(auto x : array) {
cout << x << '\n';
}
}
I'm getting the following error:
'incrementArray' : cannot convert parameter 1 from 'int (*)[10]' to
'int *[]'
What can I do to fix my code?
C-style arrays have funny syntax. To pass the array to a function, use int a[] This does not copy the array and changes to the array inside the function will modify the external array. You only need to call incrementArray(array); no & needed
You could try using std::array class which follows more normal syntax.
you have a pointer as a parameter (a reference to an array), but you wish to modify the actual thing it's pointing to, so you gotta change *a, not a.
You could use an array, vector, list, etc object that would have methods already associated to them that do most of the manipulation you could want
What you are trying to do will not work since the signature of a function taking int a[] as an argument does not contain the necessary length information needed to write a for-each loop (i.e. to instantiate the begin() and end() templates needed to use the for-each syntax). GCC's warning says this fairly clearly:
Error:(14, 19) cannot build range expression with array function parameter 'a' since
parameter with array type 'int *[]' is treated as pointer type 'int **'
I thought this might be do-able with a template, but . . .
EDIT:
It can be done with templates, just took me a moment to wrap my head around the syntax. Here is your example in working condition:
template <size_t N>
void incArray(int (&a)[N]) {
for(auto& x : a) {
++x;
}
}
int main(int argc, const char * argv[])
{
int array[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
for (auto x : array) {
cout << x << " ";
}
cout << endl;
incArray(array);
for (auto x : array) {
cout << x << " ";
}
cout << endl;
return 0;
}
There are a couple approaches you could take to increment the elements of an array, all of which require knowing where to start and where to end. The simple way of doing what you want is to just pass the start and end address pointers, but you could also pass a start address with some offset. Since you are using a C-Style array, your int element has and address int*, so your std::begin(array) is an int* to the first element while std::end(array) points to the address of the location after your last allocated element. In your program, the std::end() address points to the memory location after your 10th allocated element. If you had an array with a size allocation (int other_arr[40]), std::end() will point to the first address after the allocation (std::end(other_arr) would be std::begin(other_arr)+41). C++ has recently introduced non-member std::begin() and std::end() in the <iterator> library, which returns a pointer to the respective element locations in your C-Array.
#include <algorithm> // std::copy
#include <iostream> // std::cout
#include <iterator> // std::begin
void increment_elements(int* begin, const int* end) {
while (begin != end) {
++(*begin);
++begin;
}
}
// An increment functor for std::transform
int increase_element(int i) {
return ++i;
}
int main() {
int array[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
for (const int x : array) {
std::cout << x << ' ';
}
std::cout << '\n';
increment_elements(std::begin(array), std::end(array));
// Another way to write your print statement above
std::copy(std::begin(array),
std::end(array),
std::ostream_iterator<int>(std::cout, " "));
std::cout << '\n';
// Transform array elements through increase_element()
// and print result to cout.
std::transform(std::begin(array),
std::end(array),
std::ostream_iterator<int>(std::cout, " "),
increase_element);
std::cout << '\n';
}
The generalized version of the increment_elements() function can be found in the <algorithm> library as the function std::transform() documented here.
Since you are learning now, here are some habits that you can start to utilize:
Do not use using namespace std; at the global level. By pulling everything in the standard library into the global namespace, you "pollute" it with functionality that can be called if a function call for it exists, since it doesn't require a std:: prefix qualification. Say you were to write a function that calculated the euclidean distance between two (x,y) points, double distance(Point* p1, Point* p2). You decide to use any of the STL containers, such as <vector>. The containers utilize the <iterator> library, which has its own std::distance(T*, T*) function to calculate the distance between two addresses in memory. By bringing std into the global namespace by using namespace std;, you now have 2 functions with the same signature in the same namespace, that do 2 completely different things. This is very bad yet easily avoidable. This general guideline is probably unnecessary for small projects, but I still recommend you just don't ever do it for any project. Ever.
const or const T& your read only operations. When doing operations where you are pulling data for reading and you don't want to modify the data, initialize using const or const T&. const by itself is sufficient for primitive datatypes (int, float, double, char), but non-primitives will require const T& (T is the type). Values that are of type const T& (called const referenced) are read-only (const) and directly accessed (&).
How can I pass a two or multi dimensional array as a parameter of a function without defining its size??
Here is my example code:
void test(int *a) {
a[0][0] = 100;
}
int main() {
int a[2][2];
test(a);
cout<<a[0][0];
}
You can use a template for static sizes
template<int first, int second> void func(int(&array)[first][second]) {
}
Or a vector of vector for dynamic sizes
void func(std::vector<std::vector<int>> array) {
}
However, what you most definitely cannot do is use an int**. An int[] will decay to an int* but an int[][] will decay to an int*[]. Think about it- else, how would the language differentiate between an array of pointers, and a multi-dimensional array of values? You really should never use primitive arrays anyway, they're begging for trouble with no safety and implicit conversions up the wazoo. Grab a nice, safe std::array (or boost::array if you're in C++03) for static arrays, or std::vector for dynamic arrays.
If you're working exclusively with statically-sized, stack-allocated arrays, then a function template will do exactly what you're asking for:
#include <cstddef>
#include <ostream>
#include <iostream>
template<std::size_t N, std::size_t M>
void func(int (&arr)[N][M])
{
std::cout << "int[" << N << "][" << M << "]\n";
for (std::size_t n = 0; n != N; ++n)
for (std::size_t m = 0; m != M; ++m)
std::cout << arr[n][m] << ' ';
std::cout << '\n' << std::endl;
}
int main()
{
int i1[2][3] = { { 4, 5, 6 }, { 7, 8, 9 } };
int i2[4][2] = { { 1, 3 }, { 5, 7 }, { 9, 11 }, { 13, 15 } };
func(i1);
func(i2);
}
Passing the pointer to the array. For example, if you have a bidimensional int array you'll need to pass int** p, along with the dimensions of the array.
For built-in arrays, you have to specify the size of all dimensions but the last dimension or indexing won't work.
If your goal is just to have a function that takes multi-dimensional arrays of any size, I'd consider boost::multi_array_ref (or boost::const_multi_array_ref)
Update:
Since passing by pointer appears to be the answer that's getting the most attention (although I think the multi_array_ref is good... unless boost isn't available or something) then here's an example that flattens the array and doesn't limit you by array dimensions (although you still need size information to make it useful)
void f(int* array /* should probably pass in the size here - in this case, 4 */)
{
array[3] = 9;
}
int main()
{
int array[2][2] = { {1,2}, {3,4} };
// Note: The array is flattened here. If you truly need to remember the multi-dimensional nature, you need to pass in enough information to specify all the dimensions... maybe something like a vector<size_t> (that's what the multi_array_ref uses). I guess if you have a limited number of dimensions then a couple size_t will work for you
test(&array[0][0]);
std::cout << array[1][1] << std::endl;
return 0;
}
int a[][]
Can be passed as:
function name(int **arr) {
//your code, you can then access it just like you would have accesses your array:
arr[3][2]
}
How do I reliably get the size of a C-style array? The method often recommended seems to be to use sizeof, but it doesn't work in the foo function, where x is passed in:
#include <iostream>
void foo(int x[]) {
std::cerr << (sizeof(x) / sizeof(int)); // 2
}
int main(){
int x[] = {1,2,3,4,5};
std::cerr << (sizeof(x) / sizeof(int)); // 5
foo(x);
return 0;
}
Answers to this question recommend sizeof but they don't say that it (apparently?) doesn't work if you pass the array around. So, do I have to use a sentinel instead? (I don't think the users of my foo function can always be trusted to put a sentinel at the end. Of course, I could use std::vector, but then I don't get the nice shorthand syntax {1,2,3,4,5}.)
In C array parameters in C are really just pointers so sizeof() won't work. You either need to pass in the size as another parameter or use a sentinel - whichever is most appropriate for your design.
Some other options:
Some other info:
for C++, instead of passing a raw array pointer, you might want to have the parameter use something that wraps the array in a class template that keeps track of the array size and provides methods to copy data into the array in a safe manner. Something like STLSoft's array_proxy template or Boost's boost::array might help. I've used an array_proxy template to nice effect before. Inside the function using the parameter, you get std::vector like operations, but the caller of the function can be using a simple C array. There's no copying of the array - the array_proxy template takes care of packaging the array pointer and the array's size nearly automatically.
a macro to use in C for determining the number of elements in an array (for when sizeof() might help - ie., you're not dealing with a simple pointer): Is there a standard function in C that would return the length of an array?
A common idiom mentioned in GNU Libstdc++ documentation is the lengthof function:
template<typename T, unsigned int sz>
inline unsigned int lengthof(T (&)[sz]) { return sz; }
You can use it as
int x[] = {1,2,3,4,5};
std::cerr << lengthof(x) << std::endl;
Warning: this will work only when the array has not decayed into a pointer.
How about this?..
template <int N>
void foo(int (&x)[N]) {
std::cerr << N;
}
You can either pass the size around, use a sentinel or even better use std::vector. Even though std::vector lacks initializer lists it is still easy to construct a vector with a set of elements (although not quite as nice)
static const int arr[] = {1,2,3,4,5};
vector<int> vec (arr, arr + sizeof(arr) / sizeof(arr[0]) );
The std::vector class also makes making mistakes far harder, which is worth its weight in gold. Another bonus is that all C++ should be familiar with it and most C++ applications should be using a std::vector rather than a raw C array.
As a quick note, C++0x adds Initializer lists
std::vector<int> v = {1, 2, 3, 4};
You can also use Boost.Assign to do the same thing although the syntax is a bit more convoluted.
std::vector<int> v = boost::assign::list_of(1)(2)(3)(4);
or
std::vector<int> v;
v += 1, 2, 3, 4;
c provides no native support for this. Once an array is passed out of its declared scope, its size is lost.
You can pass the size with the array. You can even bundle them into a structure if you always to to keep the size, though you'll have some bookkeepping overhead with that.
I also agree that Corwin's method above is very good.
template <int N>
void foo(int (&x)[N])
{
std::cerr << N;
}
I don't think anybody gave a really good reason why this is not a good idea.
In java, for example, we can write things like:
int numbers [] = {1, 2, 3, 4};
for(int i = 0; i < numbers.length(); i++)
{
System.out.println(numbers[i]+"\n");
}
In C++ it would be nice instead of saying
int numbers [] = {1, 2, 3, 4};
int size = sizeof(numbers)/sizeof(int);
for(int i = 0; i < size; i++)
{
cout << numbers[i] << endl;
}
We could take it a step further and go
template <int N>
int size(int (&X)[N])
{
return N;
}
Or if that causes problems I suppose you could write explicitly:
template < int N >
int size(int (&X)[N])
{
int value = (sizeof(X)/sizeof(X[0]));
return value;
}
Then we just have to go in main:
int numbers [] = {1, 2, 3, 4};
for(int i = 0; i < size(numbers); i++)
{
cout << numbers[i] << endl;
}
makes sense to me :-)
An array expression will have its type implicitly converted from "N-element array of T" to "pointer to T" and its value will be the address of the first element in the array, unless the array expression is the operand of either the sizeof or address-of (&) operators, or if the array expression is a string literal being used to initialize another array in a declaration. In short, you can't pass an array to a function as an array; what the function receives is a pointer value, not an array value.
You have to pass the array size as a separate parameter.
Since you're using C++, use vectors (or some other suitable STL container) instead of C-style arrays. Yes, you lose the handy shorthand syntax, but the tradeoff is more than worth it. Seriously.
Now, you can use C++11's extent and rank.
By example:
#include <iostream>
#include <type_traits>
int main()
{
int a[][3] = {{1, 2, 3}, {4, 5, 6}};
std::cout << "\nRank: : " << std::rank<decltype(a)>::value;
std::cout << "\nSize: [_here_][]: " << std::extent<decltype(a), 0>::value;
std::cout << "\nSize: [][_here_]: " << std::extent<decltype(a), 1>::value;
std::cout << "\nSize: [][]_here_: " << std::extent<decltype(a), 2>::value;
}
prints:
Rank: : 2
Size: [_here_][]: 2
Size: [][_here_]: 3
Size: [][]_here_: 0
You need to pass the size along with the array, just like it is done in many library functions, for instance strncpy(), strncmp() etc. Sorry, this is just the way it works in C:-).
Alternatively you could roll out your own structure like:
struct array {
int* data;
int size;
};
and pass it around your code.
Of course you can still use std::list or std::vector if you want to be more C++ -ish.
Since c++11, there is a very convenient way:
static const int array[] = { 1, 2, 3, 6 };
int size = (int)std::distance(std::begin(array), std::end(array))+1;