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:
1cout << 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:
12345double 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:
12int 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:
1cout << 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.
Grazie per i tuoi commenti!
Chieda ad AI
Chieda ad AI
Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione
Mi faccia domande su questo argomento
Riassuma questo capitolo
Mostri esempi dal mondo reale
Awesome!
Completion rate improved to 2.94
SizeOf
Scorri per mostrare il menu
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:
1cout << 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:
12345double 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:
12int 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:
1cout << 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.
Grazie per i tuoi commenti!