Arrays and Pointers Flashcards
How is an array like a struct?
Both are aggregate data types.
T/F: Arrays can contain more than one type.
F; the types need to be uniform.
When adding the subscript operator ([]) to a variable declaration, what is the compiler being told to do?
Set aside contiguous blocks of memory (the number of blocks is given inside []), with each block of the data type’s size.
T/F: When declaring an array, the size of the array must be a constant.
T
Will the following code compile?
int nSize = 5;
int anArray[nSize];
No; ‘nSize’ must be const qualified for this to work.
What is the syntax to access the member of a struct within an array?
arrayName[int index].memberName
What is the difference between the following two declarations:
int anArray[5] = { 3, 2, 7, 5, 8 };
int anArray[5] = { 0 };
The first defines each element of the array with an initializer list, and the second sets all 5 elements of the array to 0.
Will the following code compile?
int anArray[] = { 0, 1, 2, 3, 4 };
Yes; the compiler can extrapolate the size of the array from the length of the initializer list.
How can sizeof() be used to get the number of elements in an array?
Divide the total allocated space by the size of a single element:
int nElements = sizeof(anArray) / sizeof(anArray[0]);
Why use enums to index into an array?
To avoid magic numbers:
enum StudentNames { KENNY, // 0 KYLE, // 1 STAN, // 2 BUTTERS, // 3 CARTMAN, // 4 WENDY, // 5 MAX_STUDENTS // 6 };
int anTestScores[MAX_STUDENTS]; // allocate 6 integers
anTestScores[STAN] = 76;
What is the syntax to specify an array as a parameter?
typeName arrayName[]
What does swap() do, and what is its library?
In swap(x, y), the values of the variables ‘x’ and ‘y’ are swapped. swap() is in the ‘algorithm’ library.
Articulate the steps of a selection sort.
1) Starting at index 0, search the entire array to find the smallest value
2) Swap the smallest value found with the value at index 0
3) Repeat steps 1 & 2 starting from the next index
What is the best way to initialize a multidimensional array?
With nested braces:
int anArray[3][5] = { { 1, 2, 3, 4, 5, }, { 6, 7, 8, 9, 10, }, { 11, 12, 13, 14, 15 } };
T/F, you can leave out the first dimension but not the second when declaring a multidimensional array.
T; The compiler can figure out the first dimension but not the others (it ignores braces, so it cannot intuitively figure out the array’s dimensions; it only sees a string of digits).