0

Possible Duplicate:
finding size of int array

I am curious why I get the following behaviour in this simple C++ code.

In this I try to calculate the size of a float array in 2 different places:

#include <iostream>
#include <iomanip>

using namespace std; 

void foo(float a[])
{
 int size = sizeof(a) / sizeof(float) ;

 cout << size <<std::endl;   
}



int main(int argc, char *argv[])
{

  float a[] = {22.2, 44.4, 66.6} ;

  int size = sizeof(a) / sizeof(float) ;

  cout << size <<std::endl;   

  foo(a);

  return 0;
}

Using the gcc compiler I get the output as

~: ./a.out
3
2
~: 

With other array sizes I get the first entry to be the correct size but the second always to be 2,

Now in my codes I never pass arrays without their sizes if I use arrays and I usually use the std:: vectors. But I am curious what is happening here.

What information has the 'a' lost while being passed to the function?

What is the second sizeof(a) calculating ?

Community
  • 1
  • 1
smilingbuddha
  • 14,334
  • 33
  • 112
  • 189

2 Answers2

1

The second sizeof() is calculating: sizeof(float*) / sizeof(float). The parameter of function foo is just a pointer to the first member of the array, it's similar (EDIT: identical) to float*. So sizeof(array) will give you the size of the pointer pointing to the first member, no matter if the array is int[], float[] or char[].

Ilya Kogan
  • 21,995
  • 15
  • 85
  • 141
  • It's not only "similar to `float*`", it's exactly the same in a function parameter. :) – Xeo Jan 06 '12 at 16:34
  • +1 You beat me to it by a fraction of a second :D Are there any practical differences between the passed float[] and a float* ? – daramarak Jan 06 '12 at 16:36
  • 1
    @daramarak: When encountered in a function parameter, *no*. They are exactly the same. – Xeo Jan 06 '12 at 16:45
  • I think it was a big mistake in C to disallow real array function parameters (an array return values), and even worse that when they disallowed it they just repurposed array syntax rather than making it an error. – bames53 Jan 06 '12 at 17:06
0

Having tested it here, you see that the second result is 1. I suspect (not entirely sure) that your foo argument has pointer decay going on, so it calculates the sizeof(float*) instead of just a float

Tony The Lion
  • 61,704
  • 67
  • 242
  • 415