096_memory_allocation.zig 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // In most of the examples so far, the inputs are known at compile
  2. // time, thus the amount of memory used by the program is fixed.
  3. // However, if responding to input whose size is not known at compile
  4. // time, such as:
  5. // - user input via command-line arguments
  6. // - inputs from another program
  7. //
  8. // You'll need to request memory for your program to be allocated by
  9. // your operating system at runtime.
  10. //
  11. // Zig provides several different allocators. In the Zig
  12. // documentation, it recommends the Arena allocator for simple
  13. // programs which allocate once and then exit:
  14. //
  15. // const std = @import("std");
  16. //
  17. // // memory allocation can fail, so the return type is !void
  18. // pub fn main() !void {
  19. //
  20. // var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
  21. // defer arena.deinit();
  22. //
  23. // const allocator = arena.allocator();
  24. //
  25. // const ptr = try allocator.create(i32);
  26. // std.debug.print("ptr={*}\n", .{ptr});
  27. //
  28. // const slice_ptr = try allocator.alloc(f64, 5);
  29. // std.debug.print("ptr={*}\n", .{ptr});
  30. // }
  31. // Instead of an simple integer or a constant sized slice, this
  32. // program requires a slice to be allocated that is the same size as
  33. // an input array.
  34. // Given a series of numbers, take the running average. In other
  35. // words, each item N should contain the average of the last N
  36. // elements.
  37. const std = @import("std");
  38. fn runningAverage(arr: []const f64, avg: []f64) void {
  39. var sum: f64 = 0;
  40. for (0.., arr) |index, val| {
  41. sum += val;
  42. avg[index] = sum / @intToFloat(f64, index + 1);
  43. }
  44. }
  45. pub fn main() !void {
  46. // pretend this was defined by reading in user input
  47. var arr: []const f64 = &[_]f64{ 0.3, 0.2, 0.1, 0.1, 0.4 };
  48. // initialize the allocator
  49. var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
  50. // free the memory on exit
  51. defer arena.deinit();
  52. // initialize the allocator
  53. const allocator = arena.allocator();
  54. // allocate memory for this array
  55. var avg: []f64 = ???;
  56. runningAverage(arr, avg);
  57. std.debug.print("Running Average: ", .{});
  58. for (avg) |val| {
  59. std.debug.print("{d:.2} ", .{val});
  60. }
  61. }
  62. // For more details on memory allocation and the different types of
  63. // memory allocators, see https://www.youtube.com/watch?v=vHWiDx_l4V0