-2

I am trying to write a short function which takes a pointer to an array and simply returns it's size. So far what I have is something like this:

int main (void) {
   double MyArray[3] = {0, 1, 2};

   int Temp = ArraySize(MyArray);

   return 0;
}

int ArraySize(double * MyArray) {
   return sizeof(MyArray) / sizeof(*MyArray);
}

But this doesnt seem to be working. Any help appreciated, Jack

JMzance
  • 1,704
  • 4
  • 30
  • 49

3 Answers3

3

That's impossible - the pointer simply points at the first element of the array. There's no way to extract the array size from that.

You could pass the array by reference, and infer the size as a template parameter:

template <typename T, size_t N>
size_t ArraySize(T (&)[N]) {return N;}

This will only work if you have access to the array itself (as you do in your example). If it's already decayed to a pointer, then the size information has been lost.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • Great! That's done the trick, can I check that I understand how this works...When you pass the array to the function the template call figures out how long the array is and that is then accessible in the function? – JMzance Mar 24 '14 at 11:34
  • 1
    @JackMedley: Exactly. The template infers both the element type and the array size from the (array) type of the function argument. – Mike Seymour Mar 24 '14 at 11:36
0

No it is not possible, you need to pass length in function with array. Like,

int ArraySize(double * MyArray, size_t length)
Pranit Kothari
  • 9,721
  • 10
  • 61
  • 137
0

You cannot do what you want. MyArray in function ArraySize is a pointer to a double, not an array of doubles. You must explicitly pass the array length along with the base address of the array.

ajay
  • 9,402
  • 8
  • 44
  • 71