Can someone help me with arrays?

I want to write code utilizing an array but I can not find any information regarding it
additionally I am much more comfterable writing in python and am not familiar with may of the methods

  1. is there a .length function to tell me the amount of items in an array
  2. are arrays mutable (can I add and subtract from them)

any feedback is much appreciated

arrays in C++ have a fixed size.

You could allocate one that is as large as the largest array you want to be able to support and maintain a variable that will tell you how many entries are being used.

otherwise you would have to look at Vectors or other types of containers (not an a UNO and similar)

so would that be like
add to array
var++
?

something like this:

you have global définitions

const byte maxCount = 30;
int dataStorage[maxCount];
byte nextFreeIndex = 0; // represents also the number of elements in the array

then when you have something to record, you store it at the index nextFreeIndex if it exists

if (nextFreeIndex < maxCount) {
  dataStorage[nextFreeIndex++] = analogRead(sensorPin); // whatever you want to store
} else {
  // no more space  in the array. deal with that
}
1 Like

does the ++ also update the value of nextFreeIndex?

yes, the ++ increment the value of nextFreeIndex but the expression is evaluated at the current value, so you store at the current location and the nextFreeIndex is incremented for next time (or you can see this value as the count of elements in the array as index starts at 0)

for more info on pre ou post increment / decrement see Pre-increment and Post-increment concept in C/C++?

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.