Part I
1. What is an array?
An array is an aggregate data type that lets us access many variables of the same type through a single identifier. Each variable in an array is called an element.
2. Which index would you use to access the 2nd variable in an array?
ArrayNameHere[1] because the first element in an array uses index 0. In the same way, the tenth element in an array would use index 9.
3. What can you say about the size of an array?
Fixed arrays have memory allocated at compile time. Their size is therefore predetermined because the length of the array has to be set prior to compile time. This can be limiting in certain situations because it means fixed arrays cannot have a length determined by user input at runtime for example because their length cannot be changed. To use an array that can be changed at runtime we would use a dynamic array instead.
Part II
1. How can you initialize an array?
You can initialize an array element by element but the best way to initialize an array is to do it using an initializer list, e.g. this would initialize an array of five prime numbers:
int ArrayNameHere[5] = { 2, 3, 5, 7, 11 };
int ArrayNameHere[5] { 2, 3, 5, 7, 11 };
The second example above uses the uniform initialization syntax for initializing an array in C++ 11 or later, which is where thereās no equal sign involved.
2. How can you get the size of an array in bytes?
Using the sizeof operator.
3. How can you use the function sizeof in order to calculate the number of elements in an array?
The size of the entire array is equal to the arrayās length multiplied by the size of an element. In algebraic form, this is: array size = array length * element size. We can therefore use algebra to re-arrange this equation to discover the element size. We use array[0] for the element size when we write this in our code because we know this element will exist regardless of how long the array might be.
int main()
{
int array[]{1,1,1,1};
std::cout<<āThis array has " <<sizeof(array) / sizeof(array[0])<< " elementsā <<endl;
return 0;
}
When the above is compiled, it will tell us how many elements there are, in this case it will output āThis array has 4 elementsā.
4. What happens when you try to write outside the bounds of the array?
You will get undefined behavior, e.g. it could overwrite the value of another variable or cause your program to crash.