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.
Tak for dine kommentarer!
Spørg AI
Spørg AI
Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat
Spørg mig spørgsmål om dette emne
Opsummér dette kapitel
Vis virkelige eksempler
Awesome!
Completion rate improved to 2.94
SizeOf
Stryg for at vise menuen
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.
Tak for dine kommentarer!