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 ...
Get Learning C for Arduino now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.