Review & Practice

9.3 Arrays & Pointers Relationship

Self-Assessment & Review

Part 1: The Basics

True or False & Multiple Choice

Question 1

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.

Question 2

Which use of the asterisk * is shown below?

int *ptr = &val;
  1. Multiplication
  2. Pointer Definition
  3. Indirection (Dereferencing)

Correct: Option 2

When used in a declaration, * tells the compiler the variable is a pointer.

Part 2: Checkpoints

Applying the Concepts (9.2 - 9.7)

Writing Code (9.2 & 9.3)

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;

Review (9.4 & 9.5)

Q: How do you display the value that ptr points to?

cout << *ptr;

Q: List the three uses of * in C++.

1. Multiplication, 2. Pointer Definition, 3. Indirection Operator.

Code Tracing (9.6)

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.

Result: x = 500, y = 300, z = 140

Part 3: Notation

Subscript ↔ Pointer Equivalence

Notation Conversion

Rewrite using Pointer Notation:

total = arr[index] + 5;

Answer:

total = *(arr + index) + 5;

Note: Parentheses are mandatory!

Arithmetic Logic

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

Part 4: Duality

Subscript on Pointers & Bounds

Wait, is this legal?

int *ptr = arr;
cout << ptr[2];
  • A) No, subscripts only work with arrays.
  • B) Yes, subscripts work with pointers.
  • C) No, this will cause a compile error.

Answer: B

C++ treats ptr[i] as *(ptr + i) internally.

The Danger Zone

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).

Ready for Revision!

Review the slides again if you missed any.

Key Takeaways:

  • Array name = Address of element 0.
  • arr[i] IS *(arr + i).
  • Use parentheses with indirection: *(arr + i).
  • Array names are constants; pointers are variables.