If I have an array of a fixed size depending on how it is defined and used, I typically use one of two ways to reference it.
Array type 1: Since it is a fixed size based on a define, I just use that define in all my loops referencing it.
#define MAXPLAYERS 4
int playerscores[MAXPLAYERS];
for(i=0;i<MAXPLAYERS;++i)
{
.... do something with each player
}
Array type 2: Since this array can grow as items are added to it, I use the sizeof to count the number of entries in it. The size would be converted to a constant by the compiler so there shouldn't be any runtime penalty to doing it this way.
typedef struct
{
fields....
}MYSTRUCT_DEF;
MYSTRUCT_DEF mystruct[]={
{entry 1},
{entry 2},
{entry 3...n}
};
for(i=0;i<(sizeof(mystruct)/sizeof(MYSTRUCT_DEF));++i)
{
..... do something with each entry
}
Is there a more elegant solution to handling processing of arrays without going past the end or stopping too early. Thoughts? Comments?
This will work for both of your cases, regardless of array element type:
#define ARRAY_COUNT(x) (sizeof(x)/sizeof((x)[0]))
...
struct foo arr[100];
...
for (i = 0; i < ARRAY_COUNT(arr); ++i) {
/* do stuff to arr[i] */
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With