1. What is an array?
A variable used to access multiple variables of the same type.
2. Which index would you use to access the 2nd variable in an array?
The first index is 0, second is 1. You access the indexed variable with the subscript operator [ ]: array[1];
3. What can you say about the size of an array?
For the purposes of this question, size refers to length. There are two types of array possible in C++;
- Fixed - length is set at compile time, cannot be affected by user input, cannot change: int gradeArray[20]{ }; //fixed array of 20 elements.
- Dynamic - length can be set at runtime and can be changed
More generally total array size - as in the bytes value - requires the array length multiplied by the size of the elements (data type bytes size)
Part Two
1. How can you initialize an array?
One option is to do so element by element, which is time consuming.
- int prime[5] {};
prime[0]{2};
prime[1] = 3;
prime[2] = 5;
prime[3] = 7;
prime[4] = 11;
A more efficient method is to initialize via an initialiezer list.
- int prime[5]{2, 3, 5, 7, 11};
2. How can you get the size of an array in bytes?
std::size(array) will only return length
sizeof(array) will give the byte value
3. How can you use the function sizeof in order to calculate the number of elements in an array?
std::size(array) will not work on a fixed array that has been passed to a function, so at times other methods are needed. As it is possible to use sizeof(array) to find the byte value, and we know the total byte value is the array length * the element data typeâs byte value, we can simple divide the total byte value of the array, but the byte value of the element data type, to find the length.
sizeof(array) / sizeof(array[0])
4. What happens when you try to write outside the bounds of the array?
It will result in undefined behavior as C++ will not check. It can lead to the value of other variables being overwritten or the program crashing.