Solved

sizeof array problem

Posted on 2006-06-23
7
558 Views
Last Modified: 2012-05-05
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
0
Comment
Question by:InteractiveMind
7 Comments
 
LVL 48

Accepted Solution

by:
AlexFM earned 75 total points
ID: 16967624
void outputSize( int vals [] )

The only thing that compiler knows anout vals[] parameter is that it is pointerts int. sizeof(int*) = 4. Compiler doesn't know at compile time what array is passed to outputSize function.
sizeof operator is executed by compiler at compile time, it is replaced by constant and inserted to executable code. So, in the main function, compiler knows that vals is array of 10 integers, and in outputSize function, vals is just pointer to integer.

Solution: add size parameter to the function:

void outputSize( int vals [], int size );
...

outputSize( vals, sizeof(vals)/sizeof(int) ) ;
0
 
LVL 22

Assisted Solution

by:grg99
grg99 earned 75 total points
ID: 16967663
In C, unlike Pascal, Ada, Java, Delphi, FORTRAN 90, COBOL, SNOBOL, APL, PL/I, PL/M, BASIC+, JavaScript, Simula, REXX, Spitbol, MAtLab, Perl, and a few dozen other languages, what gets passed is just the raw address of the array, and nothing else.  So it's really hard to divine the size of the array, much less the size of each element, when neither bit of info is available.  Well, that's not quite true,  if you defined the receiving array of a specific type, then you can get the sizeof an element, but that's of no use if you want to inquire about the size of arbitrary parameters. Or you can poke through the stabs debug info, if the program was compiled with debug info turned on, AND the variable is a static, global, or local variable, (not a malloc'ed variable), and you can figure out the info.  There's also the RTTi stuff, but that's also a can of worms.

So in general, you can't.

You can FAKE it by using a macro in some cases:

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


You use it like this:

 CallAndPassSize(   MyFunct, A )

and receive it like this:

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



0
 
LVL 30

Expert Comment

by:Axter
ID: 16967670
You can get the desired functionallity by making your function a template function.
0
ScreenConnect 6.0 Free Trial

Check out the updates in one game-changing release, ScreenConnect 6.0, based on partner feedback. New features include a redesigned UI that improves session organization and overall user experience. See the enhancements for yourself!

 
LVL 30

Expert Comment

by:Axter
ID: 16967674
>>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.
0
 
LVL 22

Expert Comment

by:grg99
ID: 16967675
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 ){ .... }


0
 
LVL 30

Assisted Solution

by:Axter
Axter earned 100 total points
ID: 16967686
Example code:

template < class T > 
void outputSize( T& 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 ;
}
0
 
LVL 25

Author Comment

by:InteractiveMind
ID: 16967703
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.

:)
0

Featured Post

Optimizing Cloud Backup for Low Bandwidth

With cloud storage prices going down a growing number of SMBs start to use it for backup storage. Unfortunately, business data volume rarely fits the average Internet speed. This article provides an overview of main Internet speed challenges and reveals backup best practices.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In days of old, returning something by value from a function in C++ was necessarily avoided because it would, invariably, involve one or even two copies of the object being created and potentially costly calls to a copy-constructor and destructor. A…
Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a …
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question