androidengineers.Book a session

Arrays and Memory Representation

Visualization Exercise: Array Indexing

article30 minMedium

Reinforce your understanding of array memory addressing, boundary validation, and coordinate translation through hands-on calculation problems.


Problem 1: Calculating 1D Physical Addresses

Specification

You have an array of 64-bit floating-point numbers (Double, size = 8 bytes per element).

  • Base Address: 0x5000
  • Array Size: 100 elements (indices 0 through 99)

Questions:

  1. What is the physical hexadecimal address of element at index 0?
  2. What is the physical hexadecimal address of element at index 12?
  3. If an access requests index 100, what happens at the hardware and runtime levels?

Solution & Breakdown:

  1. Index 0:

    Address = 0x5000 + (0 × 8) = 0x5000

  2. Index 12:

    12 × 8 = 96 bytes (decimal) = 0x60 (hexadecimal) Address = 0x5000 + 0x60 = 0x5060

  3. Index 100: Index 100 is out of bounds. In unmanaged languages (C/C++), this computes 0x5000 + 800 = 0x5320, leading to a buffer overflow or Segmentation Fault. In managed runtimes (Kotlin/Java/C#), bounds checks throw an ArrayIndexOutOfBoundsException before accessing the address.

Problem 2: 2D Matrix Coordinate Flattening

Specification

A high-resolution image has dimensions:

  • Width (W) = 1920 pixels
  • Height (H) = 1080 pixels
  • Flattened into a 1D IntArray(1920 * 1080).

Tasks:

  1. Write the mathematical formula to convert a 2D coordinate (x, y) into the corresponding 1D index.
  2. Calculate the 1D index for pixel (x = 450, y = 200).
  3. Write the inverse function: given 1D index 1,000,000, find its (x, y) coordinates.

Solution & Breakdown:

  1. Flattening Formula:

    Index = (y × W) + x

  2. Calculate (450, 200):

    Index = (200 × 1920) + 450 = 384,000 + 450 = 384,450

  3. Inverse Unflattening Formula:

    y = floor(Index / W) x = Index mod W For index 1,000,000: y = floor(1,000,000 / 1920) = 520 x = 1,000,000 mod 1920 = 1,000,000 - (520 × 1920) = 1,000,000 - 998,400 = 1600 Coordinates: (x = 1600, y = 520).


Challenge Implementation in Kotlin

class Matrix2D(val width: Int, val height: Int) {
    private val buffer = IntArray(width * height)

    fun get(x: Int, y: Int): Int {
        require(x in 0 until width && y in 0 until height) { "Out of bounds!" }
        return buffer[(y * width) + x]
    }

    fun set(x: Int, y: Int, value: Int) {
        require(x in 0 until width && y in 0 until height) { "Out of bounds!" }
        buffer[(y * width) + x] = value
    }

    fun getCoordinates(index: Int): Pair<Int, Int> {
        require(index in buffer.indices) { "Index out of range!" }
        val y = index / width
        val x = index % width
        return Pair(x, y)
    }
}

YOUR LEARNING JOURNEY

0 of 55 available lessons completed

Progress saved in this browser. No account needed.
Visualization Exercise: Array Indexing | Data Structures | Android Engineers