Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practices for handling variable size arrays in c / c++?

Tags:

c++

arrays

c

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?

like image 882
KPexEA Avatar asked Nov 29 '22 21:11

KPexEA


1 Answers

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] */
}
like image 87
Alex B Avatar answered Dec 05 '22 19:12

Alex B