*ฅ^•ﻌ•^ฅ* ✨✨  HWisnu's blog  ✨✨ о ฅ^•ﻌ•^ฅ

Resizing Array - Custom Function

Introduction

In this article, we will explore the use of the addToArray function to dynamically resize an array in Zig. This function is designed to handle the common problem of array resizing, where the array's capacity needs to be increased to accommodate new elements.

//
// Use addToArray to resize array
//

const std = @import("std");
const print = std.debug.print;
const pageAlloc = std.heap.page_allocator;


fn addToArray(arr: *[]i32, last_index: *usize, capacity: *usize, elem: i32) !void {
    
    if (last_index.* + 1 >= capacity.*) {
        const new_capacity = capacity.* * 2;
        const new_arr = try pageAlloc.realloc(arr.*, new_capacity * @sizeOf(i32));
        errdefer print("Realloc failed for arr\n", .{});

        arr.* = new_arr;
        capacity.* = new_capacity;
        print("Realloc successful for arr\n", .{});
    }

    arr.*[last_index.*] = elem;
    last_index.* += 1;
}

pub fn main() !void {
    
    var capacity: usize = 4;
    var arr_m = try pageAlloc.alloc(i32, capacity);
    var last_index_m: usize = 0;

    for (17..52) |i| {
        try addToArray(&arr_m, &last_index_m, &capacity, @intCast(i));
    }

    print("\nUsing addToArray to resize array: \n", .{});
    print("Capacity: {d}\n", .{capacity});
    print("Last index: {d}\n", .{last_index_m});
    print("First element: {d}\n", .{arr_m[0]});
    print("Last element: {d}\n", .{arr_m[last_index_m - 1]});
}

Pros and Cons


Check this article for implementation of ArrayList.

#code snippet #custom function #low level #programming #zig