Pointers and arrays
Pointers not only store the addresses of the variables; they also hold the address of a cell of an array. Look at the following code:
void setup() { int myVar[5] = {1, 3, 5, 6, 8}; int *myPointer; myPointer = &myVar[0]; // &myVar[0] is the address of the 1st element of myVar[5] }
Say we need to print the third element of our array. In the preceding code, myPointer
holds the value of the first element of our array. So, to access the third element, we need to increment our pointer by 2
, as follows:
myPointer = myPointer+2;
Now, if we print myPointer
value, we will get the third element of our array. Let's look at what our program and output will be for that case:
void setup() { int *myPointer; int myVar[5] = {1, 3, 5, 6, 8}; myPointer = &myVar[0]; // Holds the address of the 1st element. myPointer = myPointer + 2; // Incremented by 2 to get 3rd value of our array. Serial...