Shop OBEX P1 Docs P2 Docs Learn Events
2D arrays? — Parallax Forums

2D arrays?

lassethomsenlassethomsen Posts: 46
edited 2007-05-09 13:43 in Propeller 1
Hi.

Im in a need for a 2D array, but i cant find anyway to create one.
Does the SPIN language not support arrays larger than one dimension?

Comments

  • rjo_rjo_ Posts: 1,825
    edited 2007-05-09 13:00
    You can do anything with Spin...

    Let's say that you have a 2 dimensional array of data NM, where N is the number of columns and M is the number of rows which you wanted to store in a 1 dimensional array... and you have the base address of your 1 dimensional array.... data that you want to put into i,j would place at

    address (i,j)=base address+ i + j*N.
  • rjo_rjo_ Posts: 1,825
    edited 2007-05-09 13:10
    and a 3 dimensional array could be created

    address (i,j,k)= base address + i + j*N + k*N*M
  • KaioKaio Posts: 253
    edited 2007-05-09 13:43
    For a 2D array you can also use code like this. This avoids the multiplication if you would be use only one array as rjo_ has mentioned.
    VAR
      LONG myArray[noparse][[/noparse] 2]   '2D array with 2 rows and 10 columns
      BYTE myArray0[noparse][[/noparse]10]  'first row with 10 columns
      BYTE myArray1[noparse][[/noparse]10]  'second row with 10 columns
    
    
    PUB initArray | i, j
      
      'initialize memory pointer for rows
      LONG[noparse][[/noparse]@myArray][noparse][[/noparse] 0] := @myArray0
      LONG[noparse][[/noparse]@myArray][noparse][[/noparse] 1] := @myArray1
    
      'example how to access the 2D array
      repeat i from 0 to 1
        repeat j from 0 to 9
          BYTE[noparse][[/noparse]LONG[noparse][[/noparse]@myArray][noparse][[/noparse] i]][noparse][[/noparse] j] := 0 
    
    



    The LONG array is used to store the memory pointer of the arrays used for the rows. For performance reason it is recommendable to use the lesser size of dimension for the rows.
    The BYTE arrays stores the data, this could be also WORD or LONG.

    It is possible to use this for more dimensions, but I think it could be to complicated and not readable.
Sign In or Register to comment.