Array Size C++
The size() function of the array class in C++ determines the list container's size or the number of elements the container/array can contain. Compared to C-style arrays, C++ array classes are typically more effective and lightweight. An improved replacement for C-style arrays has been made available by introducing the array class in C++11.
Syntax of Array Size C++ Function
Syntax for using the array class size() function:
Parameters of Array Size C++ Function
Array size C++ function does not have any parameters and arguments.
Return Value of Array size C++ function
array.size() returns the number of elements/items an array container can store. The return value is of type unsigned long .
Exceptions of Array Size C++ Function
- It guarantees that no exceptions will be made.
- size() function expects 0 0 0 arguments, so if an argument is passed in the size() function, it will throw an error.
How does the Array Size C++ Function Work?
Array size C++ function is defined in the array class in the C++ libraries. It is an improved replacement for C-style arrays made available by introducing the array class in C++11.
Array size() C++ function works only with the arrays defined using the syntax of std::array declaration (Standard Template Library). It can be used in the C++ program by including the line #include<array> .
Syntax to declare an STL array:
The size() method is defined in the std::array class along with many other methods like sort() , swap() , empty() , etc. size() function takes no arguments and returns the size of the array, i.e., how many elements the array can store.
Example of Array Size C++ Function
Let's see how we declare, initialize, and print the size of the array in the output using the below C++ program:
Example C++ Program:
Output:
Explanation:
In the above C++ program, we have declared four different arrays using the array STL class. The first array is empty, and the rest are of size 6 with a different number of elements. We have printed the size of the arrays using the Array size C++ function in the output. Size represents the elements an array can store.
Alternatives to Array Size C++ Function
There are many alternative methods to calculate the size of the array. These alternative methods are listed below:
- Using sizeof() function,
- Using begin() and end() method, and
- Counting array elements using a range-based for loop.
Let's see all the alternative methods of implementation using C++ programs below:
1. Using sizeof() function:
Output:
Explanation:
sizeof(<argument>) function returns the amount of memory the <argument> object is taking. sizeof(arr) returns the total memory arr is taking, i.e., 6 (array size) * 4 (int) = 24 bytes and sizeof(arr[0]) , i.e., one element of the array is 4 bytes. sizeof(arr)/sizeof(arr[0]) = (24 ÷ 4) = 6 returns the size of the array.
2. Using begin() and end() method:
Output:
Explanation:
begin() and end() methods of the standard template library are used to get iterators pointing to the first and last element of the array, respectively. end(arr) — begin(arr) will give us the length of the array.
3. Counting array elements using range-based for loop:
Output:
Explanation:
We can use a range-based for loop and iterate over every element with an increment in the count variable. At the end of the range-based for loop count variable will contain the size of the array.
C/C++ Array Size
In C programming, arrays are used to store objects of the same type. Unlike the STL container std::vector in C++, determining the number of bytes for C arrays and the number of elements in C arrays are not straightforward.
In this blog post, I would like to discuss some of the concepts behind C arrays and how to determine the size of C arrays if it is possible.
Create Arrays
There are two types of arrays. The size of one type of the arrays would need to be known at compile-time, and the size of the other type of the arrays could be known at runtime. The former array would be created on the stack, and the latter array would be created on the heap.
To compile the program, please run the following command in the terminal.
C/C++ sizeof Operator
In C/C++, sizeof is used to determine the size of a variable or a type. Although the sizeof expressions, such as sizeof(variable) and sizeof(type) , could be used with parentheses, sizeof is a compile-time operator instead of a function in C/C++. This means that the compiler knows the exact value of sizeof(variable) and sizeof(type) at compile time.
Determine Array Size
The correct way of determining the size of arrays on the stack has been presented as follows. The size of arrays on the heap could not be determined.
To compile the program, please run the following command in the terminal.
I got the following outputs from the program. Some of the values might be different depending on the computers.
The questions is why sizeof(arr1) and sizeof(ptrArr1) result in different values. The compiler knows arr1 is neither a variable of integer nor a pointer of int, but an integer array of size 10. Therefore, sizeof(arr1) is returning the number of bytes for the array arr1 . It is some of the few cases where the array type does not decay to a pointer type. ptrArr1 , however, is just a normal pointer decayed from integer array type. Therefore, sizeof(ptrArr1) is returning the number of bytes for a single pointer ptrArr1 .
What are the differences between malloc and new?
Obviously, one major difference is that malloc does not call constructor since it does not have to know the type of variables we want to write to the memory, while new has to call a constructor.
How does delete and free know the size of an array?
It is a little bit weird that we could not determine the size of an array on the heap, but free and delete[] knows the number of bytes for the array so that they could recycle the memory accordingly. The answer is it really depends on the implementation.
There is a good diagram on the StackOverflow which I borrowed. It is a good implementation for the arrays on the heap.
free and delete[] could always look at the headers on the memory before the pointer and determine the size of the array, because free and delete[] assume all the pointers given to them are pointers pointing to the memories on the heap. sizeof , however, has no such assumptions. In addition, as mentioned above sizeof is a compile-time operator and it could not look at the potential header at runtime.
Array: size()
Array in JavaScript is a global object with many methods and properties to perform different operations. Using arrays, often one has to deal with its length. In JavaScript there are several ways to access array size.
In general the length of an array is not a fixed value, it may change or have null values as well. All in all, the length property is used to retrieve the number of items held in a particular array.
Array.size()
We should begin by saying that the size() method is not fully valid. It is not a native array method. If you really want to use the size() method, you need to connect additional libraries. For example size() is available in JQuery and other libraries, not in JavaScript. However, even in a library, the use of size() is considered irrelevant, so it is better to use the length method.
Size() is the method, which returns the length property. So there is no reason to use the method which returns property if you can call property directly.
Array.length
Length is relevant for JavaScript property, it can set the number of elements in an array or return this value. Array length property length is used both independently and in connection with some numerical properties. Some array methods (slice, join, indexOf, etc.) use the length property value in their execution. Another group of methods (push and splice), as a result of their work, update the length property of the array.
The length property is automatically updated when you add new elements to an array or delete.
Syntax
In case you want to set size of array:
the array is created using a literal and the value of the length is assigned explicitly:
the array is created using a constructor, one numeric value is passed to the constructor as an argument. An empty array will be created, the value of the length property of this array is equal to the number passed to the constructor:
In case you want to get size of array:
Return value. The method always returns a numeric value, which will be the size of the array. As a rule, it is a 32-bit integer value. By the way, the returned value is always numerically greater than the highest index in the array. This is due to the fact that the index value starts with 0.
Examples
We will show you examples of how to get the length of an array, how a property can change the length of an array, and what other ways you can use the length of an array.
In this example, we declare an array without initializing it with values and set the size of the array. Аs a result of the size of the array we get the value we set.
This time we add some values to our ‘ages’ array and ask the program how many values were added:
Such an array is called a dense array — an array where elements have contiguous indexes starting at zero.
In the next case our array is sparse , that is, some values are omitted. The program will return a number which is greater than the highest index in the current array. Because the length doesn’t indicate the actual number of elements.
Although in this example the undefined values are at the end of the array, the program still returns the value greater than the highest index:
Also you can set the length property of an array to a value that is higher than the highest index. Such an array will be named «spare».
In this example we declare an array of 5 values. Then add a value with index 20, thus forming a sparse array. Items with indexes 6 through 19 will not be specified. And as a result we get a number 21.
This also applies when all values in the array are undefined and we add an empty element by the index. As a result we will receive a number which is greater than the value declared by us.
In addition, increasing the value of the property length, new elements will not be added to the array, only the value of the property will be changed.
Setting the index we can change the appearance of the array. In particular if you set the length property to a value that is lower than the highest index in this array, all the elements whose index is greater than or equal to the new length are removed:
So the simplest way to clear an array is:
When initializing an array we can specify data type instead of numeric indexes:
In this case, we wrote the numbers as signs, and it resulted in the number 3. However, if we were to specify it as indexes of letters, words or signs, the program would not be able to recognize them:
Most often the length property is used to work with an array in a loop. In this example, let’s just output all the elements of the array in a loop.
The length of the array can be used for other purposes. For example, to find the arithmetic mean.
Let’s declare an array and a sumOfAges variable that will store the sum of all values from the array. In a cycle we add all age values and when values in an array will come to an end, we will divide the sum on length of an array.
Finally, a few more words about sparse arrays. We have already found that the property is not the actual number of elements in the array, but the largest digital index plus one.
That is, if we create an array with the length 100, but give a value to only two of them and the other will be undefined, the property will still return value 100. To determine the actual number of items you can use this code:
How to Determine Size of an Array
Basic Principle of sizeof Operator to Calculate the Size of Array
Example: int a [10];
Then, sizeof( datatype ) = sizeof( int ) = 4 bytes
Sizeof array = 10 .
So, memory required = ( 4 * 10 ) bytes = 40 bytes
Programming Example 1:
# include < stdio. h >
# include < conio. h >
int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ;
int size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; // size of array.
printf ( “ size of array = % d\n”, size ) ;
printf ( “ The array elements are : ” ) ;
for ( i = 0 ; i < size ; i ++ )
printf ( “ arr [ % d ] = % d\n”, i , arr [ i ] ) ;
Output: Size of array is 5
Explanation: Here, we declare an array named arr[] and assign some values. They are 1, 2, 3, 4, 5. If we want to determine the size of array, means how many elements present in the array, we have to write the calculation with the help of sizeof operator.
Here, the size of arr[] is 5 and each integer takes memory 4 bytes.
So, the total memory is consumed = ( 5 * 4 ) bytes.
Sizeof (arr [0]) means here the elements are integer. So, it takes memory 4 bytes.
So, the size of the array = ( 20 / 4 ) bytes = 5 bytes.
If we take character array or string instead of integer array, we can explain what happened in the next program.
Programming Example 2:
# include < stdio. h >
# include < conio. h >
char arr [ ] = { a , b , c ,d , e } ;
int size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; // size of array
printf ( “ size of array = % d \n ”, size ) ; .
printf ( “ The array elements are : ” ) ;
for ( i = 0 ; i < size ; i ++ )
printf ( “ arr [ % d ] = % c \n”, i , arr [ i ] ) ;
Output: Size of array is 5
Explanation: Here, we declare an array named arr[] and assign some values.They are <‘a’, ‘ b ‘, ‘ c ‘, ‘ d ‘, ‘ e ‘>. If we want to determine the size of array, means how many elements present in the array, we have to write the calculation with the help of sizeof() operator.
Here, the size of arr [] is 5 and each character takes memory 2 bytes.
So, the total memory is consumed = ( 5 * 2 ) bytes.
sizeof ( arr [0] ) means here the elements are character. So, it takes memory 2 bytes.
So, the size of the array = (10 / 2 ) bytes = 5 bytes.
If we take float array instead of character array, we can explain what happened in the next program.
Programming Example 3:
# include < stdio. h >
# include < conio. h >
char arr [ ] = { 1.5 , 2.5 , 3.5 , 4.5 , 5.5 } ;
int size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; //size of array
printf ( “size of array = % d \n”, size ) ;
printf ( “ array elements : ” ) ;
for ( int i = 0 ; i < size ; i ++ )
printf ( “ arr [ % d ] =% f \n ”, i ,arr [ i ] ) ;
Output: Size of array is 5
Explanation: Here, we declare an array named arr[] and assign some values.They are <1.5, 2.5, 3.5, 4.5, 5.5>. If we want to determine the size of array, means how many elements present in the array, we have to write calculation with the help of sizeof() operator.
Here, the size of arr[] is 5 and each float takes memory 8 bytes.
So, the total memory is consumed = (5 * 8) bytes.
Sizeof (arr [0]) means here the elements are float. So, it takes memory 8 bytes.
So, the size of the array = (40 / 8) bytes = 5 bytes.
Calculate the Size of Array Using Pointer
Another method to determine the size of array is by using pointer.
Programming Example 4:
Explanation: Here, we calculate the size of the array using pointer.
The above line helps us to calculate the size of the array. Here, arr means the base address of the array or address of the first index of the array.
It means the address of the second index of the array. Because we add 1 to the address of the base address.
If we subtract the address value of the array from its base address, then we get the size of each block in the array. Then, we can easily find out the size of the array by counting the total no of inputs that we have given to that particular array.
Output:
Conclusion
Clearly, it is shown that with the help of sizeof() operator pointer, we can easily calculate the length of array or the size of the array. Mainly, sizeof() operator is responsible to calculate the size of the array but additionally pointer can also support to determine the size of the array passively.