0

I have printed out my sizeof(array)/sizeof(*array) and receive the number three, but when I pass my array into my function it prints out 2 when stored into a variable and therefor iterates one less time than it should.

 void printAry(int ary[])
 {
     int size = sizeof(ary)/sizeof(ary[0]);
       cout<<size;//size will print out 2! why?
       for(int i = 0; i < size;i++)
     {
         cout<<ary[i];
     }
 }

 int main() {
     int ary[3] = {1,2,3};
     cout<<sizeof(ary[0]);

     return 0;
 }

Why is it iterating one time less than expected ?

Tony Tannous
  • 14,154
  • 10
  • 50
  • 86
  • 2
    The array is being interpreted as a _pointer_ inside the function, hence the problem. Even worse, you're passing _a single member_ of `ary` to the function, not the whole array. – ForceBru Jan 11 '17 at 17:27
  • `ary` is pointer in `printAry`, not `array of int`. – BLUEPIXY Jan 11 '17 at 17:27

2 Answers2

4

You can't use the sizeof(ary) / sizeof(ary[0]) idiom if ary is a function parameter since it will have already decayed into a pointer type: sizeof(ary) is merely the size of a pointer to int on your platform.

In C, you need to pass the size information explicitly, or adopt a convention that a particular value signals the end of the array (cf. '\0' in the C standard library string functions.)

In C++, you can use a std::vector.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
4

The reason is that arrays decay into pointers.

Basically

void printAry(int ary[])

is equivalent to:

void printAry(int* ary)

So sizeof(ary) is equal to the size of pointer to int on your system.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
Edgar Rokjān
  • 17,245
  • 4
  • 40
  • 67