By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,949 Members | 889 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,949 IT Pros & Developers. It's quick & easy.

can sizeof( <array> ) work in a function body?

P: 4
I wanted to write a function to take the tedium out of dynamically determining the total number of elements in an array.

Within the main method this is easy as I simply use:
Expand|Select|Wrap|Line Numbers
  1. sizeof( <array name> ) / sizeof( <array type> )
However I am running into an annoying problem when trying to pass an array reference to a function that is suppossed to return the same value as the above would.

my function reads:
Expand|Select|Wrap|Line Numbers
  1. int numElements( int array[] ){
  2.     int sizeOfArray = sizeof( array ) / sizeof( int );
  3.     return sizeOfArray;
  4. }
and in the main body of my program the call looks like this (simplified to demonstrate):
Expand|Select|Wrap|Line Numbers
  1. int intArray[50];
  2. cout << numElements( intArray );
However this does not print 50, instead it keeps printing 1.

I am guessing this has something to do with the fact that an array name is really just a pointer to the first element in the array, and as a result the function is only seeing the first element (and therefore is returning 1)... but is there anyway to get the function to see the whole array?

I realize I could probably save myself the headache if I just used vectors... but I kind of wanted to see if I could get this to work with arrays.

So really all I want to do is condense
Expand|Select|Wrap|Line Numbers
  1. sizeof( <array name> ) / sizeof( <array type> )
into a reusable function.

Thanks for any help!
Aug 11 '07 #1
Share this Question
Share on Google+
1 Reply

Expert Mod 5K+
P: 9,197

Use vectors.

sizeof( a thing) reports the size of the thing. In the case of an array this is the address of element 0, which is a pointer, so you get the size of the pointer.

sizeof type reports the sizof the type. In this case an int.

So you now have 4 / 4 and your array is 1 element. Oops.

Arrays in C++ are for very low level work. vector is required to be implemented as an array so all you would be doing with your function is duplicating code already done for you in vector.
Aug 11 '07 #2

Post your reply

Sign in to post your reply or Sign up for a free account.