// sizeofarray.cpp
#include <iostream>
template <typename T,int N>
int size(T (&Array)[N])
{
return N;
}
int main()
{
char p[]="Je suis trop bon, et vous?";
char q[size(p)]; // (A)
return 0;
}
I heard that an array size in C++ must be a constant expression. So char q[size(p)]
is invalid, am I right? But I got no errors when I tried
g++ -Wall sizeofarray.cpp
Why?
We can find the size of an array using the sizeof() operator as shown: // Finds size of arr[] and stores in 'size' int size = sizeof(arr)/sizeof(arr[0]);
Let first array be mPlusN[] and other array be N[] 1) Move m elements of mPlusN[] to end. 2) Start from nth element of mPlusN[] and 0th element of N[] and merge them into mPlusN[]. Below is the implementation of the above algorithm : C++
Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. In other words, two arrays are equal if they contain the same elements in the same order. Also, two array references are considered equal if both are null.
Size of an array If you create an array by initializing its values directly, the size will be the number of elements in it. Thus the size of the array is determined at the time of its creation or, initialization once it is done you cannot change the size of the array.
Like Prasoon says, it's not a constant expression. For now, you can get a constant-expression value of the size of an array like this:
template <std::size_t N>
struct type_of_size
{
typedef char type[N];
};
template <typename T, std::size_t Size>
typename type_of_size<Size>::type& sizeof_array_helper(T(&)[Size]);
#define sizeof_array(pArray) sizeof(sizeof_array_helper(pArray))
Explanation here. You basically encode the size of the array into the size of a type, then get the sizeof
of that type, giving you:
char q[sizeof_array(p)];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With