Reading & exercises¶
(3-4h) Study Chapter 6 including exercise 6.5 p.351
1. Intro array
2. Arrays
index
first element is at index 0: zero-based numbering
how do we read/write an element of an array
3. Defining arrays
type name[SIZE], e.g.,int a[10]
4. Array examples
initialization (recommended if you define it inside a function)
using a loop
size_tand its conversion specifier%zuusing an initializer list
shorthand for initializing to 0es
{0}{}has the same meaning (in C23)
Defining and using array
SIZEfor iteration over the whole arraythe book uses
#define. Modern way of defining constants, e.g.,constexpr size_t ITEM_COUNT = 10;
Summing the elements
Typical use: You do a survey, measurement, etc.
responses[STUDENT_COUNT]andfrequency=>++frequency[responses[answer]]for each answer.
Graphing array element values
Rolling a die 60,000 times and summarizing results
5. Using character arrays to store and manipulate strings
Initializing with a string:
char message[] = "Hello";null character
\0Initializing with an initializer array:
char message[] = {'H', 'e' ...}Accessing characters using indexes
Inputting:
&(location operator) not needed!Security:
scanfdoes not check the length of the input, so an overflow may occurOutputting a character array using
%s(Was introduced in section 2.7, then 3.8, and 5.10)
6. Static local arrays and automatic local arrays (remember 5.12)
staticarrays persist whole program’s lifetime, it can be better for performance compared to repetitively allocating & deallocating an array.staticvariables initialized to zero by default
7. Passing arrays to functions
int measurements[COUNT]; f(arr, COUNT)%pconversion specifier&array[0]and&arrayandarrayhave different meanings, but have the same effect in a function call[1]passing arrays by reference (address) good for performance
array as a parameter
f(int arr[], size_t size)[2]constto prevent a function from modifying array elements:f(const int a[])
8. Sorting arrays
Bubble sort: not efficient but easy to implement
9. Intro to data science case study: Survey data analysis
Mean, median, mode
10. Searching arrays
Linear search (for unsorted arrays)
Binary search (for sorted arrays)
11. Multidimensional arrays
Syntax:
a[x][y][z]...Called x-by-y-by-z array
a[x, y]not wrong syntax, but meansa[y]comma operator executes expressions from left to right
Initialization:
a[2][2] = {{11, 12}, {21, 22}}if not complete, then initialized with zero:
a[2][2] = {{11}, {21, 22}},a[0][1]becomes 0.
Setting the elements in one row
a[FIXED][variable]in a loop.Two-dimensional array manipulation case study
compilation vs execution time (or runtime)
sizeofoperator [3]sizeofreturns the size in bytes.sizeof VARIABLEorsizeof(TYPE)e.g.,
sizeof arr,sizeof(int). Types must be put inside parantheses.
(a C2Y feature) To get the number of elements
countof arrfrom<stdcountof.h>can be used, which corresponds tosizeof arr \ sizeof arr[0].[4]
13. Secure programming
Bounds checking for array subscripts:
0 <= index < ARRAY_SIZEscanf_s("%19s", string_buffer, sizeof string_buffer): Cannot lead to overflow.Don’t use strings read from the user as format-control strings.
An array
arrin its meaning (asarr) comprises all the data it stores, but if it is used in an expression, then it decays to a pointer to the array for backwards compatibility to its predecessor languages. The resulting pointer is then passed by value.There is another nice syntax:
f(int arr[static N]). This means that the compiler may assumearris notnullptrand has at leastNelements to read. This enables further optimizations.Does not only output the size of a static array but also automatic (variable-length). But how does the compiler know the size of a variable array during runtime? This can be done by saving the size of an array in the function stack and then retrieving this information via
sizeof.countofonly works where the array is defined, e.g.:#include <stdcountof.h> #include <stdio.h> constexpr size_t N = 3; void f(int arr[], size_t size) { for (size_t i = 0; i < size; ++i) printf("arr[%zu]: %d\n", i, arr[i]); puts(""); } int main() { int arr[N]; f(arr, countof arr); }It does not work in the function:
#include <stdcountof.h> #include <stdio.h> constexpr size_t N = 3; void f(int arr[], size_t size) { for (size_t i = 0; i < countof(arr); ++i) printf("arr[%zu]: %d\n", i, arr[i]); puts(""); } int main() { int arr[N]; f(arr, countof(arr)); }