kjl kjl - 4 months ago 18
C Question

C: How to generate a fixed number of objects with an array of pointers

I would like to create 11 text layers for a pebble watch face.
Without a loop the code would look something like.

static TextLayer *time_layer_a;
static TextLayer *time_layer_b;


... and so on.

How can I do this with a loop and put the pointers to the the objects in a list like structure?

list: in this case array or chain would be a better word because the collection of pointers is for a display with a fixed number of text layers. And the number of layers will not be changed during the duration of the program. In C, a list is a structure that can be dynamically resized. Using "list like" could mislead helpful people to the assumption that the sought method of chaining is expected to be dynamic. This is not correct. A structure that uses a fixed allocation of memory is preferred.

Edit: an array as suggested by John3136 worked perfectly. The array has the added benefit of generating the object pointers with its deceleration. And it's a plus that John3136 gave a way to have the code automatically adjust to the size of the array. This is a useful tool to have.

Here is the code as applied to create text layers for my watch face.

declarations:

int i;
static TextLayer* layers[11];


loading method:

// by John3136
// Note the sizeof() stuff means this works unchanged even if you change
// the number of layers.
for(i = 0; i < (short)(sizeof(layers) / sizeof(layers[0])); i++) // (short) converts unsigned interger to +- int
{
layers[i] = text_layer_create(GRect((bounds.size.w/4)*((i + 1)%4),
(bounds.size.h/PBL_IF_ROUND_ELSE(5,4))*((i > 2)
? ((i > 6)
? 3
: 2 )
: 1),
(bounds.size.w / 4) ,(bounds.size.h/PBL_IF_ROUND_ELSE(5,4))));
}


unloading method:

for(i = 0; i < (short)(sizeof(layers) / sizeof(layers[0])); i++)
{
text_layer_destroy(layers[i]);
}

Answer

Easiest way that meets your requirements as we know them: An array of 11 pointers to TextLayers.

static TextLayer*  layers[11];

You can then populate with:

int i;
// Note the sizeof() stuff means this works unchanged even if you change
// the number of layers.
for(i = 0; i < sizeof(layers) / sizeof(layers[0]); i++)
{
    layers[i] = some_func_that_creates_a_layer();
}