coming from c# with lists i have to find way to "store" some kind of obejcts.In my case i have 6
RS_DHTSensor Objects and want to add them to another object. Normaly i would have created a list and then i could add/remove them.
So i wanted to use an array instead. Now i learned, that i can only point to the objects and cant hold them in an array.
Now lets say i want to store n amount (max 64) sensor objects, i would create an array of 64.
But when i want to add one, how does i know which array element is free?
And how can i for example loop through the array and only take the pointed objects out?
RS_DHTController::RS_DHTController()
{
}
bool RS_DHTController::addSensor(RS_DHTSensor sensor)
{
// Something like this?!?
for (int i=0; i<sizeof sensors; i++) {
//How can i check now if i allready linked an object to this element??
}
return false;
}
Instead of using "sizeof" to iterate the array, declare a constant that defines the size of the array instead:
#define ARRAY_SIZE 64
DataType *the_array[ARRAY_SIZE] = {0};
...
for (i = 0; i < ARRAY_SIZE; i++) do_it(the_array[i]);
Adding = {0} to the array declaration will ensure that all elements are zero'ed / null. So whenever you need to find an empty spot, you can look for a null element. Even better would be to add a counter that holds the number of elements in the array:
int num_elements = 0;
int add(some* thing)
{
if (num_elements >= ARRAY_SIZE) return -1; //Fail, no more space
the_array[num_elements] = thing;
num_elements++;
return num_elements - 1; //Return the position added to
}
for (int i = 0; i < num_elements; i++) do_it(the_array[i]); //Only iterate occupied elements
When you add something to the array, make sure it is a pointer and not a static variable.