C++ multi dimensional array function parameter - c++

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]
}

Related

Finding array length in function [duplicate]

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.

Why can't I use a function to find the length of an array? [duplicate]

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.

Returning Arrays from C++ functions [duplicate]

I have an array int arr[5] that is passed to a function fillarr(int arr[]):
int fillarr(int arr[])
{
for(...);
return arr;
}
How can I return that array?
How will I use it, say I returned a pointer how am I going to access it?
In this case, your array variable arr can actually also be treated as a pointer to the beginning of your array's block in memory, by an implicit conversion. This syntax that you're using:
int fillarr(int arr[])
Is kind of just syntactic sugar. You could really replace it with this and it would still work:
int fillarr(int* arr)
So in the same sense, what you want to return from your function is actually a pointer to the first element in the array:
int* fillarr(int arr[])
And you'll still be able to use it just like you would a normal array:
int main()
{
int y[10];
int *a = fillarr(y);
cout << a[0] << endl;
}
C++ functions can't return C-style arrays by value. The closest thing is to return a pointer. Furthermore, an array type in the argument list is simply converted to a pointer.
int *fillarr( int arr[] ) { // arr "decays" to type int *
return arr;
}
You can improve it by using an array references for the argument and return, which prevents the decay:
int ( &fillarr( int (&arr)[5] ) )[5] { // no decay; argument must be size 5
return arr;
}
With Boost or C++11, pass-by-reference is only optional and the syntax is less mind-bending:
array< int, 5 > &fillarr( array< int, 5 > &arr ) {
return arr; // "array" being boost::array or std::array
}
The array template simply generates a struct containing a C-style array, so you can apply object-oriented semantics yet retain the array's original simplicity.
In C++11, you can return std::array.
#include <array>
using namespace std;
array<int, 5> fillarr(int arr[])
{
array<int, 5> arr2;
for(int i=0; i<5; ++i) {
arr2[i]=arr[i]*2;
}
return arr2;
}
$8.3.5/8 states-
"Functions shall not have a return type of type array or function, although they may have a return type of type pointer or reference to such things. There shall be no arrays of functions, although there can be arrays of pointers to functions."
int (&fn1(int (&arr)[5]))[5]{ // declare fn1 as returning refernce to array
return arr;
}
int *fn2(int arr[]){ // declare fn2 as returning pointer to array
return arr;
}
int main(){
int buf[5];
fn1(buf);
fn2(buf);
}
the answer may depend a bit on how you plan to use that function. For the simplest answer, lets decide that instead of an array, what you really want is a vector. Vectors are nice because the look for all the world like boring, ordinary values you can store in regular pointers. We'll look at other options and why you want them afterwards:
std::vector<int> fillarr( std::vector<int> arr ) {
// do something
return arr;
}
This will do exactly what you expect it to do. The upside is that std::vector takes care of making sure everything is handled cleanly. the downside is that this copies a very large amount of data, if your array is large. In fact it copies every element of the array twice. first it copies the vector so that the function can use it as a parameter. then it copies it again to return it to the caller. If you can handle managing the vector yourself, you can do things quite a bit more easily. (it may copy it a third time if the caller needs to store it in a variable of some sort to do more calculation)
It looks like what you're really trying to do is just populate a collection. if you don't have a specific reason to return a new instance of a collection, then don't. we can do it like this
void fillarr(std::vector<int> & arr) {
// modify arr
// don't return anything
}
this way you get a reference to the array passed to the function, not a private copy of it. any changes you make to the parameter are seen by the caller. You could return a reference to it if you want, but that's not really a great idea, since it sort of implies that you're getting something different from what you passed.
If you really do need a new instance of the collection, but want to avoid having it on the stack (and all the copying that entails), you need to create some kind of contract for how that instance is handled. the easiest way to do that is to use a smart pointer, which keeps the referenced instance around as long as anyone is holding onto it. It goes away cleanly if it goes out of scope. That would look like this.
std::auto_ptr<std::vector<int> > fillarr( const std::vector<int> & arr) {
std::auto_ptr<std::vector<int> > myArr(new std::vector<int>);
// do stuff with arr and *myArr
return myArr;
}
For the most part, using *myArr works identically to using a plain vanilla vector. This example also modifies the parameter list by adding the const keyword. Now you get a reference without copying it, but you can't modify it, so the caller knows it'll be the same as before the function got to it.
All of this is swell, but idiomatic c++ rarely works with collections as a whole. More normally, you will be using iterators over those collections. that would look something more like this
template <class Iterator>
Iterator fillarr(Iterator arrStart, Iterator arrEnd) {
Iterator arrIter = arrStart;
for(;arrIter <= arrEnd; arrIter++)
;// do something
return arrStart;
}
Using it looks a bit odd if you're not used to seeing this style.
vector<int> arr;
vector<int>::iterator foo = fillarr(arr.begin(), arr.end());
foo now 'points to' the beginning of the modified arr.
What's really nice about this is that it works equally well on vector as on plain C arrays and many other types of collection, for example
int arr[100];
int *foo = fillarr(arr, arr+100);
Which now looks an awful lot like the plain pointer examples given elsewhere in this question.
This:
int fillarr(int arr[])
is actually treated the same as:
int fillarr(int *arr)
Now if you really want to return an array you can change that line to
int * fillarr(int arr[]){
// do something to arr
return arr;
}
It's not really returning an array. you're returning a pointer to the start of the
array address.
But remember when you pass in the array, you're only passing in a pointer.
So when you modify the array data, you're actually modifying the data that the
pointer is pointing at. Therefore before you passed in the array, you must realise
that you already have on the outside the modified result.
e.g.
int fillarr(int arr[]){
array[0] = 10;
array[1] = 5;
}
int main(int argc, char* argv[]){
int arr[] = { 1,2,3,4,5 };
// arr[0] == 1
// arr[1] == 2 etc
int result = fillarr(arr);
// arr[0] == 10
// arr[1] == 5
return 0;
}
I suggest you might want to consider putting a length into your fillarr function like
this.
int * fillarr(int arr[], int length)
That way you can use length to fill the array to it's length no matter what it is.
To actually use it properly. Do something like this:
int * fillarr(int arr[], int length){
for (int i = 0; i < length; ++i){
// arr[i] = ? // do what you want to do here
}
return arr;
}
// then where you want to use it.
int arr[5];
int *arr2;
arr2 = fillarr(arr, 5);
// at this point, arr & arr2 are basically the same, just slightly
// different types. You can cast arr to a (char*) and it'll be the same.
If all you're wanting to do is set the array to some default values, consider using
the built in memset function.
something like:
memset((int*)&arr, 5, sizeof(int));
While I'm on the topic though. You say you're using C++. Have a look at using stl vectors. Your code is likely to be more robust.
There are lots of tutorials. Here is one that gives you an idea of how to use them.
http://www.yolinux.com/TUTORIALS/LinuxTutorialC++STL.html
This is a fairly old question, but I'm going to put in my 2 cents as there are a lot of answers, but none showing all possible methods in a clear and concise manner (not sure about the concise bit, as this got a bit out of hand. TL;DR 😉).
I'm assuming that the OP wanted to return the array that was passed in without copying as some means of directly passing this to the caller to be passed to another function to make the code look prettier.
However, to use an array like this is to let it decay into a pointer and have the compiler treat it like an array. This can result in subtle bugs if you pass in an array like, with the function expecting that it will have 5 elements, but your caller actually passes in some other number.
There a few ways you can handle this better. Pass in a std::vector or std::array (not sure if std::array was around in 2010 when the question was asked). You can then pass the object as a reference without any copying/moving of the object.
std::array<int, 5>& fillarr(std::array<int, 5>& arr)
{
// (before c++11)
for(auto it = arr.begin(); it != arr.end(); ++it)
{ /* do stuff */ }
// Note the following are for c++11 and higher. They will work for all
// the other examples below except for the stuff after the Edit.
// (c++11 and up)
for(auto it = std::begin(arr); it != std::end(arr); ++it)
{ /* do stuff */ }
// range for loop (c++11 and up)
for(auto& element : arr)
{ /* do stuff */ }
return arr;
}
std::vector<int>& fillarr(std::vector<int>& arr)
{
for(auto it = arr.begin(); it != arr.end(); ++it)
{ /* do stuff */ }
return arr;
}
However, if you insist on playing with C arrays, then use a template which will keep the information of how many items in the array.
template <size_t N>
int(&fillarr(int(&arr)[N]))[N]
{
// N is easier and cleaner than specifying sizeof(arr)/sizeof(arr[0])
for(int* it = arr; it != arr + N; ++it)
{ /* do stuff */ }
return arr;
}
Except, that looks butt ugly, and super hard to read. I now use something to help with that which wasn't around in 2010, which I also use for function pointers:
template <typename T>
using type_t = T;
template <size_t N>
type_t<int(&)[N]> fillarr(type_t<int(&)[N]> arr)
{
// N is easier and cleaner than specifying sizeof(arr)/sizeof(arr[0])
for(int* it = arr; it != arr + N; ++it)
{ /* do stuff */ }
return arr;
}
This moves the type where one would expect it to be, making this far more readable. Of course, using a template is superfluous if you are not going to use anything but 5 elements, so you can of course hard code it:
type_t<int(&)[5]> fillarr(type_t<int(&)[5]> arr)
{
// Prefer using the compiler to figure out how many elements there are
// as it reduces the number of locations where you have to change if needed.
for(int* it = arr; it != arr + sizeof(arr)/sizeof(arr[0]); ++it)
{ /* do stuff */ }
return arr;
}
As I said, my type_t<> trick wouldn't have worked at the time this question was asked. The best you could have hoped for back then was to use a type in a struct:
template<typename T>
struct type
{
typedef T type;
};
typename type<int(&)[5]>::type fillarr(typename type<int(&)[5]>::type arr)
{
// Prefer using the compiler to figure out how many elements there are
// as it reduces the number of locations where you have to change if needed.
for(int* it = arr; it != arr + sizeof(arr)/sizeof(arr[0]); ++it)
{ /* do stuff */ }
return arr;
}
Which starts to look pretty ugly again, but at least is still more readable, though the typename may have been optional back then depending on the compiler, resulting in:
type<int(&)[5]>::type fillarr(type<int(&)[5]>::type arr)
{
// Prefer using the compiler to figure out how many elements there are
// as it reduces the number of locations where you have to change if needed.
for(int* it = arr; it != arr + sizeof(arr)/sizeof(arr[0]); ++it)
{ /* do stuff */ }
return arr;
}
And then of course you could have specified a specific type, rather than using my helper.
typedef int(&array5)[5];
array5 fillarr(array5 arr)
{
// Prefer using the compiler to figure out how many elements there are
// as it reduces the number of locations where you have to change if needed.
for(int* it = arr; it != arr + sizeof(arr)/sizeof(arr[0]); ++it)
{ /* do stuff */ }
return arr;
}
Back then, the free functions std::begin() and std::end() didn't exist, though could have been easily implemented. This would have allowed iterating over the array in a safer manner as they make sense on a C array, but not a pointer.
As for accessing the array, you could either pass it to another function that takes the same parameter type, or make an alias to it (which wouldn't make much sense as you already have the original in that scope). Accessing a array reference is just like accessing the original array.
void other_function(type_t<int(&)[5]> x) { /* do something else */ }
void fn()
{
int array[5];
other_function(fillarr(array));
}
or
void fn()
{
int array[5];
auto& array2 = fillarr(array); // alias. But why bother.
int forth_entry = array[4];
int forth_entry2 = array2[4]; // same value as forth_entry
}
To summarize, it is best to not allow an array decay into a pointer if you intend to iterate over it. It is just a bad idea as it keeps the compiler from protecting you from shooting yourself in the foot and makes your code harder to read. Always try and help the compiler help you by keeping the types as long as possible unless you have a very good reason not to do so.
Edit
Oh, and for completeness, you can allow it to degrade to a pointer, but this decouples the array from the number of elements it holds. This is done a lot in C/C++ and is usually mitigated by passing the number of elements in the array. However, the compiler can't help you if you make a mistake and pass in the wrong value to the number of elements.
// separate size value
int* fillarr(int* arr, size_t size)
{
for(int* it = arr; it != arr + size; ++it)
{ /* do stuff */ }
return arr;
}
Instead of passing the size, you can pass the end pointer, which will point to one past the end of your array. This is useful as it makes for something that is closer to the std algorithms, which take a begin and and end pointer, but what you return is now only something that you must remember.
// separate end pointer
int* fillarr(int* arr, int* end)
{
for(int* it = arr; it != end; ++it)
{ /* do stuff */ }
return arr;
}
Alternatively, you can document that this function will only take 5 elements and hope that the user of your function doesn't do anything stupid.
// I document that this function will ONLY take 5 elements and
// return the same array of 5 elements. If you pass in anything
// else, may nazal demons exit thine nose!
int* fillarr(int* arr)
{
for(int* it = arr; it != arr + 5; ++it)
{ /* do stuff */ }
return arr;
}
Note that the return value has lost it's original type and is degraded to a pointer. Because of this, you are now on your own to ensure that you are not going to overrun the array.
You could pass a std::pair<int*, int*>, which you can use for begin and end and pass that around, but then it really stops looking like an array.
std::pair<int*, int*> fillarr(std::pair<int*, int*> arr)
{
for(int* it = arr.first; it != arr.second; ++it)
{ /* do stuff */ }
return arr; // if you change arr, then return the original arr value.
}
void fn()
{
int array[5];
auto array2 = fillarr(std::make_pair(&array[0], &array[5]));
// Can be done, but you have the original array in scope, so why bother.
int fourth_element = array2.first[4];
}
or
void other_function(std::pair<int*, int*> array)
{
// Can be done, but you have the original array in scope, so why bother.
int fourth_element = array2.first[4];
}
void fn()
{
int array[5];
other_function(fillarr(std::make_pair(&array[0], &array[5])));
}
Funny enough, this is very similar to how std::initializer_list work (c++11), but they don't work in this context.
to return an array from a function , let us define that array in a structure;
So it looks something like this
struct Marks{
int list[5];
}
Now let us create variables of the type structure.
typedef struct Marks marks;
marks marks_list;
We can pass array to a function in the following way and assign value to it:
void setMarks(int marks_array[]){
for(int i=0;i<sizeof(marks_array)/sizeof(int);i++)
marks_list.list[i]=marks_array[i];
}
We can also return the array. To return the array , the return type of the function should be of structure type ie marks. This is because in reality we are passing the structure that contains the array. So the final code may look like this.
marks getMarks(){
return marks_list;
}
the Simplest way to do this ,is to return it by reference , even if you don't write
the '&' symbol , it is automatically returned by reference
void fillarr(int arr[5])
{
for(...);
}
int *fillarr(int arr[])
You can still use the result like
int *returned_array = fillarr(some_other_array);
if(returned_array[0] == 3)
do_important_cool_stuff();
As above mentioned paths are correct. But i think if we just return a local array variable of a function sometimes it returns garbage values as its elements.
in-order to avoid that i had to create the array dynamically and proceed. Which is something like this.
int* func()
{
int* Arr = new int[100];
return Arr;
}
int main()
{
int* ArrResult = func();
cout << ArrResult[0] << " " << ArrResult[1] << endl;
return 0;
}
Source: https://www.tutorialspoint.com/cplusplus/cpp_return_arrays_from_functions.htm
C++ does not allow to return an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array's name without an index.
If you want to return a single-dimension array from a function, you would have to declare a function returning a pointer as in the following example:
int * myFunction() {
.
.
.
}
C++ does not advocate to return the address of a local variable to outside of the function so you would have to define the local variable as static variable.
Applying these rules on the current question, we can write the program as follows:
# include <iostream>
using namespace std;
int * fillarr( );
int main ()
{
int *p;
p = fillarr();
for ( int i = 0; i < 5; i++ )
cout << "p[" << i << "] : "<< *(p + i) << endl;
return 0;
}
int * fillarr( )
{
static int arr[5];
for (int i = 0; i < 5; ++i)
arr[i] = i;
return arr;
}
The Output will be:
p[0]=0
p[1]=1
p[2]=2
p[3]=3
p[4]=4
template<typename T, size_t N>
using ARR_REF = T (&)[N];
template <typename T, size_t N>
ARR_REF<T,N> ArraySizeHelper(ARR_REF<T,N> arr);
#define arraysize(arr) sizeof(ArraySizeHelper(arr))
and what about:
int (*func())
{
int *f = new int[10] {1,2,3};
return f;
}
int fa[10] = { 0 };
auto func2() -> int (*) [10]
{
return &fa;
}
Actually when you pass an array inside a function, the pointer to the original array is passed in the function parameter and thus the changes made to the array inside that function is actually made on the original array.
#include <iostream>
using namespace std;
int* func(int ar[])
{
for(int i=0;i<100;i++)
ar[i]=i;
int *ptr=ar;
return ptr;
}
int main() {
int *p;
int y[100]={0};
p=func(y);
for(int i=0;i<100;i++)
cout<<i<<" : "<<y[i]<<'\n';
}
Run it and you will see the changes
And why don't "return" the array as a parameter?
fillarr(int source[], size_t dimSource, int dest[], size_t dimDest)
{
if (dimSource <= dimDest)
{
for (size_t i = 0; i < dimSource; i++)
{
//some stuff...
}
}
else
{
//some stuff..
}
}
or..in a simpler way (but you have to know the dimensions...):
fillarr(int source[], int dest[])
{
//...
}
A simple and elaborate example, so that I can refer here if I forget the concept and need help.
#include <iostream>
using namespace std;
int *ReturnArray(int arr[], int size)
{
static int MinMax[2] = {0, 0}; // must use static, else address would be deleted after the return is reached
MinMax[0] = arr[0];
MinMax[1] = arr[size - 1];
return MinMax;
}
int main()
{
int arr[] = {1, 2, 3};
int size = sizeof(arr) / sizeof(*arr);
int *ans; // pointer to hold returned array
ans = ReturnArray(arr, size); // only pointer can receive the return, not an array
cout << "Min: " << ans[0] << " Max: " << ans[1];
return 0;
}
Here's a full example of this kind of problem to solve
#include <bits/stdc++.h>
using namespace std;
int* solve(int brr[],int n)
{
sort(brr,brr+n);
return brr;
}
int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
int *a=solve(arr,n);
for(int i=0;i<n;i++)
{
cout<<a[i]<<endl;
}
return 0;
}
i used static array so that while returning array it should not throw error as you are returning address of local variable...
so now you can send any locally created variable from function by making it as static...as it works as global variable....
#include<iostream>
using namespace std;
char *func(int n)
{
// char a[26]; /*if we use this then an error will occur because you are
// returning address of a local variable*/
static char a[26];
char temp='A';
for(int i=0;i<n;i++)
{
a[i]=temp;temp++;
}
return a;
}
int main()
{
int n=26;
char *p=func(n);
for(int i=0;i<n;i++)
cout<<*(p+i)<<" ";
//or you can also print like this
for(int i=0;i<n;i++)
cout<<p[i]<<" ";
}
Just define a type[ ] as return value, like:
private string[] functionReturnValueArray(string one, string two)
{
string[] x = {one, two};
x[0] = "a";
x[1] = "b";
return x;
}
.
.
.
function call:
string[] y;
y = functionReturnValueArray(stringOne, stringTwo)

sizeof in function c++ [duplicate]

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.

How to reliably get size of C-style array?

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;