Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using size of one array in another array

// 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?

like image 250
Ideone Avatar asked Sep 30 '10 13:09

Ideone


People also ask

How do you find the size of an array in another function?

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]);

How do I merge one array into another array?

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++

Can I set two arrays equal to each other?

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.

Can we assign different size to array?

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.


1 Answers

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)];
like image 158
GManNickG Avatar answered Oct 04 '22 00:10

GManNickG