- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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; }
Advertisements