NXC  Version 1.2.1 r5
 All Data Structures Files Functions Variables Groups Pages
Arrays

NXC also support arrays.

Arrays are declared the same way as ordinary variables, but with an open and close bracket following the variable name.

int my_array[]; // declare an array with 0 elements

To declare arrays with more than one dimension simply add more pairs of square brackets. The maximum number of dimensions supported in NXC is 4.

bool my_array[][]; // declare a 2-dimensional array

Arrays of up to two dimensions may be initialized at the point of declaration using the following syntax:

int X[] = {1, 2, 3, 4}, Y[]={10, 10}; // 2 arrays
int matrix[][] = {{1, 2, 3}, {4, 5, 6}};
string cars[] = {"honda", "ford", "chevy"};

The elements of an array are identified by their position within the array (called an index). The first element has an index of 0, the second has index 1, and so on. For example:

my_array[0] = 123; // set first element to 123
my_array[1] = my_array[2]; // copy third into second

You may also initialize local arrays or arrays with multiple dimensions using the ArrayInit function. The following example shows how to initialize a two-dimensional array using ArrayInit. It also demonstrates some of the supported array API functions and expressions.

task main()
{
int myArray[][];
int myVector[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
byte fooArray[][][];
ArrayInit(myArray, myVector, 10); // 10 vectors
ArrayInit(fooArray, myArray, 2); // 2 myArrays
fooArray[1] = myArray;
myArray[1][4] = 34;
int ax[], ay[];
ArrayBuild(ax, 5, 7);
ArrayBuild(ay, 2, 10, 6, 43);
int axlen = ArrayLen(ax);
ArraySubset(ax, ay, 1, 2); // ax = {10, 6}
if (ax == ay) {
// compare two arrays
NumOut(0, LCD_LINE1, myArray[1][4]);
}
}

NXC also supports specifying an initial size for both global and local arrays. The compiler automatically generates the required code to correctly initialize the array to zeros. If an array declaration includes both a size and a set of initial values the size is ignored in favor of the specified values.

task main()
{
int myArray[10][10];
int myVector[10];
//ArrayInit(myVector, 0, 10); // 10 zeros in myVector
//ArrayInit(myArray, myVector, 10); // 10 vectors myArray
}

The calls to ArrayInit are not required since we specified the initial sizes in the preceding array declarations, which means the arrays were already initialized to all zeros. In fact, the myVector array declaration is not needed unless we have a use for myVector other than initializing myArray.