Problem with Clearing Screen in Zig using VGA Memory Pointer

I’m new to the Zig language and I’m trying to learn how to interact directly with hardware. Specifically, I want to clear the screen from top to bottom using VGA memory.

I tried to use a pointer to the VGA memory address, but I got an error. Here’s the code I tried:

const std = @import("std");

const VGA_MEMORY: i32 = 0xB8000;
const SCREEN_WIDTH: i32 = 80;
const SCREEN_HEIGHT: i32 = 25;
const WHITE_ON_BLACK: i32 = 0x0F;

pub fn clear_screen() void {
	const vga_ptr: *u16 = @ptrFromInt(VGA_MEMORY);
	const space: u16 = (0x20 | (WHITE_ON_BLACK << 8));

	for (0..(SCREEN_WIDTH * SCREEN_HEIGHT)) | iterator | {
		vga_ptr[iterator] = space;
	}

	return;
}

When I try to build the code, I get the following error message:

zig build                                                       1 ↵
install
└─ install ignition
   └─ zig build-exe ignition Debug native 1 errors
second-stage/helpers/clean-screen.zig:46:10: error: type '*u16' does not support indexing
  vga_ptr[iterator] = space;
  ~~~~~~~^~~~~~~~~~
second-stage/helpers/clean-screen.zig:46:10: note: operand must be an array, slice, tuple, or vector

What I don’t understand:

  1. I want to clear the screen by writing a value to the VGA memory.
  2. In C, this would work by simply indexing into a pointer, but Zig seems to have some different rules regarding pointers and indexing.

Could someone please explain what I’m doing wrong and how to fix it?

Zig pointers can point to a single item or to multiple items.

The single item pointer declaration is const ptr: *T and you can use ptr.* to access the single T element value.
The multiple item pointer declaration is const ptr: [*]T and you can use ptr[n] to access the nth element.

To fix the code declare vga_ptr type as [*]u16.

Welcome to ziggit :slight_smile:

2 Likes