Solved

sizeof array problem

Posted on 2006-06-23
7
548 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
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
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

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Errors will happen. It is a fact of life for the programmer. How and when errors are detected have a great impact on quality and cost of a product. It is better to detect errors at compile time, when possible and practical. Errors that make their wa…
Written by John Humphreys C++ Threading and the POSIX Library This article will cover the basic information that you need to know in order to make use of the POSIX threading library available for C and C++ on UNIX and most Linux systems.   [s…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.

760 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

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now