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]);

 

Did you like this?
Tip admin with Cryptocurrency

Donate Bitcoin to admin

Scan to Donate Bitcoin to admin
Scan the QR code or copy the address below into your wallet to send some bitcoin:

Donate Bitcoin Cash to admin

Scan to Donate Bitcoin Cash to admin
Scan the QR code or copy the address below into your wallet to send bitcoin:

Donate Ethereum to admin

Scan to Donate Ethereum to admin
Scan the QR code or copy the address below into your wallet to send some Ether:

Donate Litecoin to admin

Scan to Donate Litecoin to admin
Scan the QR code or copy the address below into your wallet to send some Litecoin:

Donate Monero to admin

Scan to Donate Monero to admin
Scan the QR code or copy the address below into your wallet to send some Monero:

Donate ZCash to admin

Scan to Donate ZCash to admin
Scan the QR code or copy the address below into your wallet to send some ZCash:

1 Comment


  1. 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