Link to home
Start Free TrialLog in
Avatar of InteractiveMind
InteractiveMindFlag for United Kingdom of Great Britain and Northern Ireland

asked on

sizeof array problem

Here's the code:


#include <stdafx.h>
#include <iostream>
#include <iomanip>
using namespace std ;

void outputSize( int vals [] )
{
      cout << "In outputSize():  {" << sizeof(vals)/sizeof(vals[0]) << "}" << endl ;
}

int main()
{
      int vals [] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } ;

      // output array size
      cout << "In main():  {" << sizeof(vals)/sizeof(vals[0]) << "}" << endl ;
      
      // pass array to function, where it's size should be outputted
      outputSize( vals ) ;

      return 0 ;
}


And here's the output:

  In main():  {10}
  In outputSize():  {1}


For some reason, it would seem that 'sizeof(vals)' in the outputSize() function is getting the sizeof a single element within the array, rather than the total amount of memory occupied by the entire array...

- Why is this?
- How can I solve it?


Thanks

btw: Am using VS 2005 Pro now
ASKER CERTIFIED SOLUTION
Avatar of AlexFM
AlexFM

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Axter
You can get the desired functionallity by making your function a template function.
>>You can FAKE it by using a macro in some cases:

I recommed using a template over a macro, because macros enter all namespaces, where-as a template stays within it's own namespace.
Avatar of grg99
grg99

OOPS, I goofed, try this to get both pieces of info:

#define CallAndPassSize(Func,Array)       Func( (void* )&Array, (sizeof(Array)/sizeof(Array[0])), (sizeof(Array[0])) )


You use it like this:

 CallAndPassSize(   MyFunct, A )

and receive it like this:

void MyFunct( void * ArbitraryArray, unsigned int ArrayLength, unsigned int ArrayElements ){ .... }


SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of InteractiveMind

ASKER

Thanks very much all.

Being a Java geek myself, and having limited C++ experience, I had no idea about this -- but you've all done a great job explaining it. It's much clearer now.

:)