Reputation: 157
I had the online coding interview today and I really struggled while trying to calculate the size of the array. Could you please help me with how can I measure the sizeof array here? I tried my best but no luck please help here.
#include<iostream>
#include<map>
#include<vector>
using namespace std;
void arraysize(int* a) {
cout << "size1: "<<sizeof(a) << endl;
cout << "size2: " << sizeof(a[0]) << endl;;
}
int main()
{
int array1[] = { 1,2,3,4,5,6,7,8 };
arraysize(array1);
return 0;
}
Result: size1: 4 size2: 4
Upvotes: 0
Views: 500
Reputation: 63
simply divide sizeof(array1)
by sizeof(int)
. it will give you total element in array. because sizeof(array1)
will give total bytes in the array. for example sizeof(array1)
= int * 8 because your array is int so int is 4 byte answer is 4*8 = 32.Now you have to divide it again by 4 cause its in byte.
cout << "Size of the Array is : " << sizeof(array1)/sizeof(int) << endl;
put above code in your main function to get result
Upvotes: 0
Reputation: 7736
Easiest way to get the size of an array:
#include <iostream>
using namespace std;
int main(void) {
int ch[5], size;
size = sizeof(ch) / sizeof(ch[0]);
cout << size;
return 0;
}
Output: 5
Upvotes: 0
Reputation: 505
sizeof(a) returns the number of bytes in array, sizeof(int) returns the number of bytes in an int, ergo sizeof(a)/sizeof(int) returns the array length
Upvotes: 0
Reputation: 2255
In most cases, when you pass an array to a function, the array will be converted to a pointer. This is called an array-to-pointer decay. Once this decay happens, you lose the size information of the array. That is, you can no longer tell the size of the original array from the pointer.
However, one case in which this conversion / decay will not happen is when we pass a reference to the array. We can take advantage of this property to get the size of an array.
#include<iostream>
template<typename T, size_t N>
size_t asize(T (&array)[N])
{
return N;
}
int main()
{
int array1[] = { 1,2,3,4,5,6,7,8 };
std::cout << asize(array1) << std::endl; // 8
return 0;
}
In the above case, to the template function asize
, we pass a reference to an array of type T[N]
, whose size is N
. In this case, it is array type int[8]
. So the function returns N
, which is size 8.
Upvotes: 3
Reputation: 5511
C
style array
's decay to pointer
's when passed to a function like this.
The first cout
statement is printing the size of a pointer
on your machine.
The second cout
statement is printing the size of an integer
.
Use one of the following solutions in order to pass the size of the array
to the function.
template<std::size_t N>
void ArraySize( int ( &array )[ N ] )
{
std::cout << "Array size: " << N << '\n';
}
void ArraySize( int* array, std::size_t size )
{
std::cout << "Array size: " << size << '\n';
}
template<std::size_t N>
void ArraySize( std::array<int, N>& array )
{
std::cout << "Array size: "<< array.size( ) << '\n';
}
Upvotes: 0