sizeof

hello every one....i am facing a little problem...my instructor used sizeof(x)/sizeof(int) to find the size of an array x[7]....but i coudlnt get it...can any one please elaborate it for me???
Last edited on
say u wanna find out size of int X[7];

assume u donno its an array of seven integers.

sizof(x)/sizeof(int)
ie
sizeof(seven integers)/sizeof(one integer)=7
ie the size of array
Maybe you use a pointer instead of the array. For example consider the following code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

void func( int array[7] )
{
   std::cout << "In func: " << sizeof( array ) / sizeof( int ) << std::endl;
}

int main()
{
   int array[7];

   std::cout << "In main: " << sizeof( array ) / sizeof( int ) << std::endl;

   return 0;
}



Here in the main the result of outputting will be 7 - size of the array. However in func the result of outputting will be usually equal to 1. What is the matter?
When an array is pased to a function which has a parameter declared as int array[7] or int array[] the array is converted to the pointer to its first element. So the declaration

void func( int array[7] );

is equivalent to

void func( int *p );


Size of a pointer to int usually is equal to 4, And size of int usually is equal to 4. So in the function you will get 1.
Last edited on
If you pass the array by reference :
1
2
3
4
void func( int (&a)[7] )
{
   std::cout << "In func: " << sizeof( a ) / sizeof( int ) << std::endl;
}

then it will output the correct result (7).

Someone here, in this forum had a very nice solution to get the size for any static array :
1
2
3
4
template<class T, std::size_t N>
std::size_t asize(const T (&)[N]) {
	return N;
}


Of course, you should always use boost::array or std::array if you're using static arrays.


Edit : 666th ;)
Last edited on
thanks guys....for your help....especially anirudh sn, you rocked :-)
Topic archived. No new replies allowed.