Self-Assessment & Review
True or False & Multiple Choice
An array name is essentially a pointer that can be reassigned to point to another array in memory during runtime.
Answer: False
Array names are constant pointers. They cannot be changed after definition.
Which use of the asterisk * is shown below?
int *ptr = &val;
Correct: Option 2
When used in a declaration, * tells the compiler the variable is a pointer.
Applying the Concepts (9.2 - 9.7)
Task 1: Define and initialize a pointer to a float named
fltPtr.
float *fltPtr = nullptr;
Task 2: Assign the address of value to ptr.
ptr = &value;
Q: How do you display the value that ptr points to?
cout << *ptr;
Q: List the three uses of * in C++.
int x = 50, y = 60, z = 70;
int *ptr = &x;
*ptr *= 10;
ptr = &y;
*ptr *= 5;
ptr = &z;
*ptr *= 2;
State the final values of x, y, and z.
Subscript ↔ Pointer Equivalence
Rewrite using Pointer Notation:
total = arr[index] + 5;
Answer:
total = *(arr + index) + 5;
Note: Parentheses are mandatory!
If numbers is an array of int (4 bytes), and its address is
0x2000...
What is the address of *(numbers + 2)?
Answer: 0x2008
Address + (index * sizeof(type)) = 0x2000 + (2 * 4) = 0x2008
Subscript on Pointers & Bounds
int *ptr = arr;
cout << ptr[2];
Answer: B
C++ treats ptr[i] as
*(ptr + i) internally.
True or False: C++ will stop the program if a pointer tries to access memory outside an array's bounds.
False
C++ performs no bounds checking. It will happily let you access invalid memory (leading to garbage data or crashes).
Review the slides again if you missed any.
Key Takeaways:
arr[i] IS *(arr + i).*(arr + i).