How to print size of array parameter in a function in C++?


The size of a data type can be obtained using sizeof(). A program that demonstrates the printing of the array parameter in a function in C++ is given as follows.

Example

 Live Demo

#include <iostream>
using namespace std;
int func(int a[]) {
   cout << "Size: " << sizeof(a);
   return 0;
}
int main() {
   int array[5];
   func(array);
   cout << "\nSize: " << sizeof(array);
   return 0;
}

Output

The output of the above program is as follows.

Size: 8
Size: 20

Now let us understand the above program.

In the function func(), the size of a is displayed which is 8 because the array in main() is passed as a pointer and a points to the start of array. So, sizeof(a) displays the size of the pointer which is 8. The code snippet that shows this is as follows.

int func(int a[]) {
   cout << "Size: " << sizeof(a);
   return 0;
}

In the function main(), the size of array is displayed which is 20. This is because the size of int is 4 and the array contains 5 int elements. The code snippet that shows this is as follows.

int main() {
   int array[5];
   func(array);
   cout << "\nSize: " << sizeof(array);
   return 0;
}

Updated on: 26-Jun-2020

204 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements