Declare and initialize array of arrays

Post

Posted
Rating:
#1 (In Topic #823)
Trainee

Code (gambas)

  1. Public Sub Main()
  2.   Dim c As New Float[][2]
  3.   c[0] = [1.23, 2.34]
  4.   Print "c[0][0]", c[0][0]
  5.   Print "c[0][1]", c[0][1]
  6.   c[1] = [3.45, 4.56]
  7.   c[2] = [5.67, 6.78]
  8.   c[3] = [7.89, 8.90]
  9.  
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?
Online now: No Back to the top

Post

Posted
Rating:
#2
Avatar
Regular
AMUR-WOLF is in the usergroup ‘Regular’

kwhitefoot said

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:

Code (gambas)

  1.   Dim c As New Float[4, 2]
  2.   c[0, 0] = 1.23
  3.   c[0, 1] = 2.34
  4.   c[1, 0] = 3.45
  5.   c[1, 1] = 4.56
  6.   c[2, 0] = 5.67
  7.   c[2, 1] = 6.78
  8.   c[3, 0] = 7.89
  9.   c[3, 1] = 8.90
  10.  
  11.   Print "c[0, 0] = ", c[0, 0]
  12.  

If you want to use array of arrays instead of two-dimensional array, you should do such thing:

Code (gambas)

  1.   Dim c As New Float[][4]
  2.  
  3.   c[0] = New Float[2]
  4.   c[0][0] = 1.23
  5.   c[0][1] = 2.34
  6.  
  7.   c[1] = New Float[2]
  8.   c[1][0] = 3.45
  9.   c[1][1] = 4.56
  10.  
  11.   c[2] = New Float[2]
  12.   c[2][0] = 5.67
  13.   c[2][1] = 6.78
  14.  
  15.   c[3] = New Float[2]
  16.   c[3][0] = 7.89
  17.   c[3][1] = 8.90
  18.  
  19.   Print "c[0][0] = ", c[0][0]
  20.  
Online now: No Back to the top

Post

Posted
Rating:
#3
Avatar
Guru
cogier is in the usergroup ‘Guru’
For array of arrays have a look at the attached program that converts between Arabic and Roman number formats.

Code (gambas)

  1. 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.

Attachment
Online now: No Back to the top
1 guest and 0 members have just viewed this.