Opening the reading…
Opening the reading…
PROGRAMMING FUNDAMENTALS › C++ FUNDAMENTALS
The declaration int marks[4] = {12, 7, 19, 3}; reserves storage for four int elements as one uninterrupted block. The values are placed in index order: marks[0] is 12, marks[1] is 7, marks[2] is 19, and marks[3] is 3. Allocation means reserving the bytes needed for that block. It does not mean asking for four unrelated pieces of storage.
int marks[4] = {12, 7, 19, 3};
// The values occupy the elements in index order:
// marks[0] = 12, marks[1] = 7, marks[2] = 19, marks[3] = 3Which layout matches int marks[4] = {12, 7, 19, 3};?
Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
On this run, one int occupies 4 bytes. The first element, marks[0], begins at byte offset 0 inside the block. Moving from one index to the next moves forward by 4 bytes, so marks[1] begins at offset 4, marks[2] at offset 8, and marks[3] at offset 12. In general, the starting offset of an element is its index multiplied by the size of one element.
The index identifies an element, while the byte offset identifies where that element begins relative to the start of the block. Because the slots are adjacent and equal in size, the same calculation works for every index in marks. The values differ, but the spacing between their starting positions does not.
sizeof(marks[0]) asks for the size of one element, so it produces 4 bytes on this run. sizeof(marks) asks for the size of the whole array, so it produces 16 bytes here. The result follows from four adjacent elements, each occupying 4 bytes: 4 * 4 = 16. The 4-byte size of int is a fact about this run, not a promise that every machine uses the same size.
int marks[4] = {12, 7, 19, 3};
sizeof(marks[0]); // 4 on this run
sizeof(marks); // 16 on this runEnter the starting byte offset of marks[3] and the total result of sizeof(marks) on this run.
int marks[4] = {12, 7, 19, 3};Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
A local array has automatic storage. Its storage becomes available when execution reaches its declaration inside the enclosing block, and it remains available while execution stays in that block. When execution leaves the block, the storage for marks is released automatically. The array does not continue to exist for code that runs after the closing brace.
{
int marks[4] = {12, 7, 19, 3};
// marks exists here
}
// marks no longer exists here