Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
SizeOf | Data Types and Arrays
C++ Intermediate | Mobile-Friendly
course content

Contenido del Curso

C++ Intermediate | Mobile-Friendly

C++ Intermediate | Mobile-Friendly

1. Data Types and Arrays
2. References & Pointers
3. Dynamic Memory
4. Functions

bookSizeOf

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:

1
cout << sizeof(int);
copy

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:

12345
double a; cout << sizeof(a) << endl; double b = 2.1; cout << sizeof(b);
copy

We can also apply this operator to get the length of the array:

12
int numbers[] = {1, 2, 3, 4, 5}; cout << sizeof(numbers);
copy

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:

1
cout << sizeof(numbers)/sizeof(int) << endl;
copy

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.

question-icon

Write the function to find the length of the double array arr:

double arr[] = {1.2, 2.4, 3.7};
cout <<
()sizeof();
3

Click or drag`n`drop items and fill in the blanks

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 1. Capítulo 3
some-alt