Array

From Microduino Wiki
Revision as of 03:32, 22 August 2016 by Fengfeng (talk) (Created page with "Arrays<br> An array is a collection of variables which can be accessed. Arduino arrays is based on C language, thus it will become very complicated, however, using a simple a...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Arrays

An array is a collection of variables which can be accessed. Arduino arrays is based on C language, thus it will become very complicated, however, using a simple array is relatively simple.
Create (declare) an array.

The following ways all can be used to create(declare)arrays.

  myInts [6];
  myPins [] = {2,4,8,3,6};
  mySensVals [6] = {2,4,-8,3,2};
  char message[6] = "hello";
 

You declare an uninitialized array, such as myPins.

In myPins, we declare an array, the size of which is not clear, and the compiler can calculate the size of the element, and create an appropriate-size array.

Of course, you can also initialize the size of the array, for example within mySensVals. Please pay attention to that when you declare a char array, the size you initialize must be greater than the number of the elements to accommodate the null characters.
Access the array

The index of an array is from 0, which is to say, the array initialization mentioned above, the first element of an array is index 0, so:

mySensVals [0] == 2,mySensVals [1] == 4,

And so on.

This also means within an array containing ten elements, index 9 is the last element, so ,

  int myArray[10] = {9,3,2,4,3,2,7,8,9,11};
  // the value of myArray[9] is 11
  // myArray[10], this index is invalid, it will be arbitrary random information(memory address)
 

Because of this, you must be careful when you visit an array. If the data to be visited exceed the end of the array(the index number is larger than the size of the array that you declare -1), it will read data from other memory. Reading data from these places doesn’t have any effect in addition to generate invalid data. Writing data into the random access memory is a bad idea, which usually leads to bad results, such as a system crash or program failure. To troubleshoot this error is also a difficult task. Different from Basic or JAVA, C language compiler won’t check whether the array you visit is larger than the one you declare.
Specify the value of an array.

  mySensVals [0] = 10;

Access to a value from an array:

  X = mySensVals [4];

Arrays and loops

Arrays are usually operated within for loops, and the loop counter can be used to access each array element, for example, to print the elements in an array via a serial port, you can do:

  int i;
  for (i = 0; i < 5; i = i + 1) {
  Serial.println(myPins[i]);
  }

[Return to Arduino Syntax Manual]