Reading & exercises¶
(3-4h) Study Chapter 7 including exercise 7.6 (p. 409). The following sections are optional:
7.12 Function pointers: is not part of the course learning goals.
7.13 Secure C programming
7.1 What do pointers enable?
7.2 Pointer variable definitions and initialization
a variable usually contains a value. A pointer contains the address (as a value) of another variable that contains a value. The pointer points to the variable.
Declaration,
int *ptrNaming
board_ptr,p_boardmultiple definitions
int *ptr1, *ptr2NULLuse
nullptrin C23
7.3 Pointer operations
&operator (address)*operator (indirection)*nullptrcauses fatal error
&*same as*&, they complement each other
7.4 Passing arguments to functions by reference
Until now, we can only return a single value, e.g.,
int,float. Using pointers we can return larger data structures and multiple values.pass-by-value and pass-by-reference to a function
pointer parameters in functions
f(int *n_ptr)f(int[] arr)interchangeable withf(int *arr)(compiler converts to the latter)
7.5 Using the
constqualifier with pointersfor enforcing principle of least privilege
four variations:
... pointer
to ... data
example syntax
non-constant
non-constant
char *strnon-constant
constant
const char *strconstant
non-constant
char *const strconstant
constant
const char *const strConsequence of modifying const data: Compiler error
Passing
structures vs arrays: pass-by-value vs pass-by-reference
7.6 Bubble sort using pass-by-reference
swap(&arr[j], &arr[j + 1])Placing the function prototype only in the function that is the single user
has the same effect as using
#includeinside a function if including the header does not cause problems.
7.7
sizeofoperatorreturns the size in bytes
works also on variable-length arrays
countofreturns the number of elements <=>sizeof(arr) / sizeof(arr[0])sizeof arrinside a function vs outsidesizeof int,sizeof doubleetc
7.8 Pointer expressions and pointer arithmetic
++,--,ptr + x,ptr1 + ptr2ptr + 2=> 2 means 2 * size-of-what-ptr-points-tothis arithmetic enables array operations like
int arr[30]; arr[10]=>*(&arr[0] + 10 * sizeof(int))
ptr2 - ptr1= number of elements (not bytes) between two addressesvoid *exists, but cannot be referenced
7.9 Relationship between pointers and arrays
arr[3]=>*(arr + 3)&arr[3]=>arr + 3pointer/subscript notation:
int *ptr = arr; ptr[1]same asarr[1]arr += 3invalid, we cannot modify an array’s startCopying strings with arrays and pointers
7.10 Arrays of pointers
common use: array of strings
const char *names[] = {"Amanda", "Aman"}
7.11 Case study: Card shuffling and dealing
Assigning numbers from 1 to 52 to
deck[SUITS][FACES]
7.12 Function pointers
7.13 Secure C programming
scanf_setc check fornullptr