Declare and initialize array of arrays

New to Gambas? Post your questions here. No question is too silly or too simple.
Post Reply
kwhitefoot
Posts: 2
Joined: Thursday 3rd February 2022 7:50pm

Declare and initialize array of arrays

Post by kwhitefoot »

Public Sub Main()
  Dim c As New Float[][2]
  c[0] = [1.23, 2.34]
  Print "c[0][0]", c[0][0]
  Print "c[0][1]", c[0][1]
  c[1] = [3.45, 4.56]
  c[2] = [5.67, 6.78]
  c[3] = [7.89, 8.90]
End
If you run this subroutine it runs until it tries to assign to c[2]. Is this expected behaviour? I expected it to fail when assigning to c]0]. I can get the behaviour I expected by adding the statement c.Clear immediately after the declaration.

So I have two questions:
- What is the idiomatic way of populating an array of arrays?
- What is the idiomatic way of declaring a fixed size array of arrays?
User avatar
AMUR-WOLF
Posts: 21
Joined: Sunday 6th February 2022 8:41am
Location: Russia

Re: Declare and initialize array of arrays

Post by AMUR-WOLF »

kwhitefoot wrote: Monday 21st February 2022 6:58pm So I have two questions:
- What is the idiomatic way of populating an array of arrays?
- What is the idiomatic way of declaring a fixed size array of arrays?
If you certainly know that you need 4 rows with 2 columns, you should create a two-dimensional array:
  Dim c As New Float[4, 2]
  c[0, 0] = 1.23
  c[0, 1] = 2.34
  c[1, 0] = 3.45
  c[1, 1] = 4.56
  c[2, 0] = 5.67
  c[2, 1] = 6.78
  c[3, 0] = 7.89
  c[3, 1] = 8.90
  
  Print "c[0, 0] = ", c[0, 0]
If you want to use array of arrays instead of two-dimensional array, you should do such thing:
  Dim c As New Float[][4]
  
  c[0] = New Float[2]
  c[0][0] = 1.23
  c[0][1] = 2.34
  
  c[1] = New Float[2]
  c[1][0] = 3.45
  c[1][1] = 4.56
  
  c[2] = New Float[2]
  c[2][0] = 5.67
  c[2][1] = 6.78
  
  c[3] = New Float[2]
  c[3][0] = 7.89
  c[3][1] = 8.90
  
  Print "c[0][0] = ", c[0][0]
User avatar
cogier
Site Admin
Posts: 1118
Joined: Wednesday 21st September 2016 2:22pm
Location: Guernsey, Channel Islands

Re: Declare and initialize array of arrays

Post by cogier »

For array of arrays have a look at the attached program that converts between Arabic and Roman number formats.
Dim sRoman As String[][] = [[""], ["", "M", "MM", "MMM", "MMMM", "MMMMM", "MMMMMM", "MMMMMMM", "MMMMMMMM", "MMMMMMMMM"], ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"], ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"], ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"]]
Also have a look here.
RomanNumberConverter-1.0.tar.gz
(17.99 KiB) Downloaded 138 times
Post Reply