0

When passing an array to a function and using sizeof() in the fuction, it just returns the size of a single element (4). Is there a way to fix this? And I'm limited to only using arrays, not vectors/templates.

void arraysize(int arr[]){
    cout << sizeof(arr) << endl;
}

int main(){
    int a[15];
    arraysize(a);                  //4
    cout << sizeof(a) << endl;     //60
}

Output:

4
60
Joe Defill
  • 439
  • 1
  • 4
  • 16

2 Answers2

3

You have to pass the array by reference to keep the size info:

void arraysize(int (&arr)[15]);

with template to auto deduce the size:

template <std::size_t N>
void arraysize(int (&arr)[N]);

So without template/STL, you have to pass the the size info in some way:

void arraysize(int *arr, std::size_t size);

or

void arraysize(int *arr, int* end);
Jarod42
  • 203,559
  • 14
  • 181
  • 302
1

You need to read up on array decay.

Community
  • 1
  • 1
Bulletmagnet
  • 5,665
  • 2
  • 26
  • 56
  • Also adjustment. Array decay isn't the only thing going on in OP's code. There has to be a context that requires the array decay in the first place. – juanchopanza Feb 23 '15 at 08:37
  • The context that requires array decay is the function call. See the first sentence of http://www.lysator.liu.se/c/c-faq/c-2.html#2-4 – Bulletmagnet Feb 23 '15 at 08:49
  • Only because the function takes a pointer, due to *adjustment*. If the function took something that didn't require a pointer to element of the array, there'd be no decay. – juanchopanza Feb 23 '15 at 09:01