How to calculate the length of an array in C++?

In C++, you can use the sizeof operator to calculate the length of an array. The sizeof operator returns the number of bytes the array occupies, so you can divide the total number of bytes by the number of bytes per element to get the array length.

For example, using the sizeof operator to calculate the length of an integer array:

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

In the example above, sizeof(arr) returns the total number of bytes occupied by the integer array arr, while sizeof(arr[0]) returns the number of bytes for a single element in the integer array. By dividing the total number of bytes by the number of bytes for a single element, we can obtain the length of the integer array.

It should be noted that this method only applies to static arrays; for dynamically allocated arrays or arrays pointed to by pointers, the sizeof operator cannot be used to calculate the length.

Leave a Reply 0

Your email address will not be published. Required fields are marked *