1

I'm calculating the size of the array using following code

int  arr[] = {1, 2, 3, 4, 5, 6};
int size = *(&arr + 1) - arr;

This gives me 6 as output. However, when I create a function with the same code, the size becomes -8. What could be the reason for this behaviour.

int sizeArr(int arr[])
{
    int size = *(&arr + 1) - arr;
    return size;
}
Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
Lawhatre
  • 1,302
  • 2
  • 10
  • 28
  • 4
    dupe of [determine size of array if passed to function](https://stackoverflow.com/questions/968001/determine-size-of-array-if-passed-to-function) and many others. research _array to pointer decay_, _array passing to function_, etc. – underscore_d May 11 '21 at 16:12
  • "*This gives me 6 as output*" That doesn't mean it's the size of the array. – Nicol Bolas May 11 '21 at 16:15

2 Answers2

3

It's the way pointer arithmetic works.

An expression of the form

pointer + amount

is, informally speaking at least, evaluated as

pointer + sizeof(*pointer) * amount

In other words, pointer arithmetic adds sizeof units of the type.

In your first snippet, sizeof(arr) is the size of the actual array. But in the function, it's the size of the pointer to an element in the array due to pointer decay!

See for yourself - output sizeof(arr) in both cases, and note the difference.

(To add to the bewildering list of rules, the evaluation of sizeof(arr) is one of those instances where arr does not decay to a pointer type! Oh joy!)

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
2
int sizeArr(int arr[])
{
    int size = *(&arr + 1) - arr;
    return size;
}

The arr parameter in the sizeArr function contains no size information (as compared to if you pass an array by reference to the function), and arguments passed to it will _decay to a pointer). Thus, the size you are attempting to calculate does some (mis-)calcuations based on a pointer, not on an object of array type.

dfrib
  • 70,367
  • 12
  • 127
  • 192