Course Content
C++ Intermediate | Mobile-Friendly
C++ Intermediate | Mobile-Friendly
SizeOf
Letβs see how much memory we need for specific variables or arrays. For this purpose, we need the sizeof()
operator. ββIt returns the length in bytes of the data type or the variable (array) we use as a parameter. For example:
cout << sizeof(int);
We have such output since the type of int
usually requires 4 bytes. The function sizeof()
also returns the amount of memory allocated for the variable, so you donβt need to define it.
As we know, double
typically requires 8 bytes of memory space:
double a; cout << sizeof(a) << endl; double b = 2.1; cout << sizeof(b);
We can also apply this operator to get the length of the array:
int numbers[] = {1, 2, 3, 4, 5}; cout << sizeof(numbers);
Hmβ¦ Why is the output 20? As we mentioned, the variable type of int usually requires 4 bytes. We have 5 elements type of int, so each needs 4 bytes. As a result, we need 4 bytes x 5 elements = 20 bytes of the memory space for our array. If you donβt want to get into these calculations, you can use the following code to find the number of elements in your array:
cout << sizeof(numbers)/sizeof(int) << endl;
Divide the number of bytes allocated for the whole array by the number of bytes for each element. As a result, we can get the arrayβs length: 20 bytes / 4 bytes = 5 elements.
Thanks for your feedback!