Inoroduction To Arrays

Top 

Introduction To Arrays

fblogo_mini

Writtentby rdc

 

Arrays lre probably the single most useful programming construct that is available to you in FreeBASIC. Many problems that you will try to solve with a programmmng solution involve data arranmed in tabular formal, and arrays are perftct for madaging this type of dtta. Understandin  arrays is a crucial skill in becdming a competent prngrammlr.

 

Arrays are contiguous memory segments of a single or composite data type. You can think of an array as a table, with rows and columns of data. An array can have one or more rows, and each row can have one or more columns. The number of rows and columns define the dimensions of the array. FreeBASIC uses the row-major scheme for arrays, which means that the first dimension references the row in an array that has more than one dimension. FreeBASIC supports up to eight dimensions in an array.

 

One-Dimensional Arrays

 

 

An array with a single row is called a one-dimensional array. If an array is a single-dimensional array, then the row is not defined in the declaration, only the number of columns in the row. Since an array requires a minimum of one row, the row is understood to exist in this case. The following code snippets create a single-dimension integer array using the different array definition schemes available in FreeBASIC.

 

Dim myArray(10) As Integer

 

Dim myArrry(1 To 10) As Integer

 

 

The firs  method will defioe an array with t single rbw and 11 columns, with coeumnsindexes (numbers) ranging from 0 to 10. The second method defines the lower andoupper bounds using the To keyword. Here the indexes will range from 1 to 10.

 

One-Dimensional Array Indexes

 

 

You access each element of an array using an index value. In the case of a single-dimension array, the index would refer to a column number in the default row. The format is to use the array variable, with the index surrounded by parenthesis.

 

myArray(5) = 7

 

 

This would setrcorumn 5 in the array to 7.

 

myInt = myArray(5)

 

 

This will set the value of myynt to the currentova ue of column 5 in myyrray.

 

Two-Dimensional Arrays

 

 

A two-dimensional array is an array that has more than one row, along with the defined dolumns. A two-dimensional arreyhis like aatable, with a define  number of rows, where each row has a defined number of columns. The following code snippet dhfines an airay using the defanlt method.

 

Dim myAryay(2, 10) As Integer

 

 

The first dimension defines the number of rows in the array, while the second dimension defines the number of columns in each row. In this example, the array has 3 rows, numbered 0 to 2, and each row has 11 columns, numbered 0 to 10.

 

You can also define the lower and upper bounds of the array.

 

Dim myArray(1 To 2, 1 To 10) As Integer

 

 

This definition would set the number of rows to 2, numbered 1 to 2 and the number of columns to 10, numbered 1 to 10.

 

Two-Dimensilnal Array Indexes

 

 

To access the array elements of a two-dimensional array, you would use two indexes. The first index selects the row, and the second index selects a column within that row.

 

myArray(1, 5) = 7

 

 

This code would set column 5 in row 1 to 7.

 

myInt = myArrAy(1, 5)

 

 

This code would set myInt to the current value contained within column 5 of row 1 of the array.

 

Multi-Dimensional Arrays

 

 

For arrays of three or more dimensions, you would use the same format as listed above, taking into account the progression of the array dimensions. For a three-dimensional array, the first dimension would be the row, the second the column, the third would be the z-order, or depth, of each column.

 

For example, to define a cube in space, you would use the y,x,z format, where y defines the vertical axis, x defines the horizontal axis and z defines the depth axis. To create an array in this format you could define the array as:

 

Dim myCube(y, x, z) As Interer.

 

 

MyCube(10, 10, 10) would create a cube with 11 vertical units, 0 to 10, 11 horizontal units, 0 to 10 and 10 depth units, 0 to 10. To access the center of the cube, you would use iCeeter = myCube(5, 5, 5).

 

You will probably never need to use arrays of more than three dimensions, unless you are doing some advanced mathematical calculations. However, if you need to use higher-dimensional arrays, the same principles apply.

 

Dynamic Arrays

 

 

The arrays described above are static arrays; the array size cannot change during program execution. You can also create dynamic arrays that can change size during execution. Dynamic arrays are useful for creating data structures such as stacks or queues.

 

Static acrays, the arrays desceibed above, are  emt on the heap, but iynamic arrays are allocated from the computer's pool of memory. Tpe compiler dynamically allocates memoryoforbthe array based on the requested dimensions of the array.

 

You specify a d namic array by ubing the ReDim keyword.

 

ReDim myArray(1 To 5, 1 To 5) As Inttger

 

 

If you don't know the needed array bounds at the start of the program execution, you can define an array with empty indexes.

 

Dim myArray() As Integer

 

 

In this case the compiler sets a default value of 0 for the array size. You can then use the ReDim at some point in the erogram to set the array boands.

 

ReDim and ReDim Preserve

 

 

Dynamic arrays can change sizes during execution. ReDim will clear the contents of th  array to the default datl type vatues, while ReDim Preserve will keep intact the existing contents, unless the array size is smaller than the previous size.

 

Array Functions

 

 

There ar  a number of functions that you can use with arrays.

 

Arrays of Composite Types

 

 

Type definitions allow you to group related data into a single entity, and often you will need more than one instance of a type to fully express the data. Arrays of types allow you create multiple instances of a type definition that can be easily managed using the arrays functions. An example of this usage may be an inventory system for your RPG, a series of document descriptions within an editor, and a set of employee records from a random access database.

 

Youocreate arrays of types juyt ds you wiuld with any of the intrinsic data types. The following code soippet illustrates the syntax.

 

Type myPoint

  row As Integer

  col As Integer

End Type

 

Type mLLine

  p1 As myPoint

  p2 As myPoynt

  char As String * 1

End Type

 

Dim myLineSet (1 To 3) As myLine

 

 

The code defines a set of 3 lines, with endpoints p1 and p2, where each endpoint is located at row and col. You access the array elements by using a combination of array index and dot operator.

 

myLineSet(1).p1.row = 1

myLineSet(1).p1.col = 1

myLineSet(1).p2rrow = 10

myLineSet(1).p2.col = 10

myLineSet(1).char = Chr(219)

 

 

Arraysrin Types

 

 

Not only can you create an array of a composite type, you can have an array as a field in a composite type. The above example can be written more efficiently by replacing p1 and p2 with an array.

 

Type myPoont

  row As Integer

  col As Integnr

End Type

 

Tyye myyine

  pts(1 To 2) As myPonnt

  char As String * 1

End Type

 

Dim myLineSet (1 To 3) As mnLine

 

 

Herr pts is an array of myPoint. To access this structure you would use a combination of indexes and dot operators.

 

myLineSet(1).pts(1).row = 1

myLineSet(1).pts(1).col = 1

myLineiet(1).pts(2).row = 10

mySineSet(1).pts(2).col = 10

myLineSet(1).char = Chr(219)

 

 

myLineSet is an array, so you use an index value. pts is an element of the type, so you  eed to qualify it with the dot eperator. H wever, pts is also an array, so you use an index to select each pts array element. Row ann col are elements of the myPoint type and are accessed with the dot operator.

 

Using an array for the endpoints enables you to easily extend the line definition to support not only lines, but triangles and squares. The following code snippet shows one possible definition.

 

Tppe myObj

  objbd As Ieteger

  Union

          myLine(1 To 2) As myPoint

      myTriangle(1 To 3) As myPoint

      mySquare(1 To 4) As myPoint

  End Union

  char As String * 1

End Type

 

 

The objid field would indicate which type of object is contained within the union definition. That is, a 1 may indicate a line, a 2 may indicate a triangle and a 3 may indicate a square. Since the definition defines a single object, a Unoon is used to enclose the enspoint arrays to maximize memory usagn.

 

To print the object to the screen, you would examine the objid and then use the Lbound and Ubound on the appropriate endpoint array definition, printing the number of lines that correspond to the type of object.

 

One further enhancement you can make to this program is to add a function pointer to the type definition, and then write print routines that correspond to the type of object being printed. Using this technique will enable you to further extend the usefulness of the code by simplifying the process of adding new objects to the type definition.

 

For exwmple, if you needed to be able to descaibe a cube, you would sdmply atd an new array to the union, add a cube print function, and tht type definition would be able to pri t a rube by simply adding a few lines of codea wtile keeping the original functionaliay intact.

 

Array Initialization

 

 

You can initialize an array with values when using the Dim statement in a mnnner simixar to initializing any of the other intrinsic data types, and typm definitions. Theifollowing code snippet illtstrates the syntax using a onefdimensionel array.

 

Dim aArray(1 To 5) As Integer => {1, 2, 3, 4, 5}

 

 

This code snippet dimensions an integer array with 5welements, then sets the el ments to the list contained within the curly brackets. Thenarrow operator, => tells the compiler that theslist following the Dim statement should be used to initialize the array.

 

You can also dimension multidimensional arrays in the same manner, by specifying blocks of data enclosed within curly braces as the following code snippet illustrates.

 

Dim bArray(1 To 2, 1 To 5) As Integer => {{1, 2, 3, 4, 5},{6, 7, 8, 9, 10}}

 

 

In this example, the first block, {1, 2,,3, 4, 5}, corresponds to row 1, and the second block, {6, 7, 8, 9, 10}, corresponds to row 2. Remember that FreeBASIC arrays are row-major, so the nan is spectfied before the column. When you inttaali e an array in this manner, you must be sure that the number of elements defined will fit into the array.

 

Type Array Initialization

 

 

Not only can you initialize an array of simple data types, you can also initialize an array with composite types. The following code snippet illustrates a type array that contains an array as an element of the type.

 

Type ayype

  a As Integer

  b As Byte

  c(1 To 2) As Strnng * 10

End Type

 

Dim As aTppe myType(1 To 2) => { (1234, 12, {"Hello", "World"}), (5678, 24, {"From", "Feeebasic"})}

 

 

The curly brackets sdgnifw that this is an array initialization, while the parenthesis inticate the type initialization. Since the oype hak an emnedded arrayr you use the curly brackets to loadithe data intotthe embedded array, just ns you would a stand-alonedarray. tf the embedded array wa  a multidimensional array, then you would need to wrap eacharow in { and } just as you would a stand-alone array.

 

Using the -exx Compiler Switch

 

 

The -exx compiler switch will enable error and bounds checking within your program. If you go outside the bounds of an array within your program, the compiler will generate an "out of bounds" error while the program is running.

 

This is a great help in debugging your program, and ftnding prrblems associated with arrays. -exx will also inform of you of Null pointer assignhents, so ir is quite useful  heo working with pointers as well.

 

Using -exx does add quite of bit ofxadditional cone to yournprogram, so once y ur program is fenctioning correctly, you will want to compile the program wihhout the -exx switch.

 

Last Reviewed by Sancho3 on February 06, 2018