I'm new to C++ programming and I'm trying to get the size of an array. Can anybody explain me why this happens? I've tried running the code in runnable.com and the same result shows.
I'm sure this is not the right way to do it. If possible, can you suggest any EASY way to get the size of that kind of array?
#include <iostream>
using namespace std;
int main ()
{
int set1[] = {1, 9, 3, 50, 31, 65};
int set234[] = {3, 5, 5};
cout << sizeof(set1) << endl;
cout << sizeof(set234) << endl;
cout << "When sizeof() return value is divided by 4"<< endl;
cout << sizeof(set1) / 4 << endl;
cout << sizeof(set234) / 4 << endl;
return 0;
}
****************************************************************
Output:
24
12
When sizeof() return value is divided by 4
6
3
****************************************************************
**EDIT : Thank you for your responses. flies away :D
The size of an array is equal to the sum of sizes of all its elements. As in your example you deal with arrays of type int then it seems sizeof( int ) in your system is equal to 4, So as the first array has 6 elements then its size is equal to 6 * sizeof( int )
that is 24. The size of the second array is equal to 3 * sizeof( int )
that is 12.
If for example sizeof( int ) in your system would be equal to 8 then the size of the first array would be equal to 48 ( 6 * sizeof* int ) ) and the size of the second array would be equal to 24 ( 3 * sizeof( int ) ).
So if you want for example to know how many elements there are in an array you can calculate this the following way
sizeof( YouArray ) / sizeof( YourArray[0] )
or
sizeof( YouArray ) / sizeof( ElementType )
sizeof
returns the number of bytes, not the number of elements. Mostly you should avoid arrays; use std::vector
or std::array
, both provide an easy way to get the number of elements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With