How to get the size of an array in C++?

The answer is using the sizeof operator.

The important thing is that sizeof always returns the number of bytes of the operand regardless it is an array or a basic type. So to get the number of elements in an array, you should use the code below:

int a[]={1,2,3,4,5};
int n=sizeof(a)/sizeof(a[0]);

 

If you like my content, please consider buying me a coffee. Buy me a coffeeBuy me a coffee Thank you for your support!

1 Comment

  1. Visitor

    Since C++17 you can simply use std::size(a)

    You also have std::array (C++11) that is a recommended replacement to C arrays.

Leave a Reply