I've an array of type uint8_t* const with 6 items, defined like this

uint8_t* const neighbourSet[] = {PEER1, PEER2, PEER3, PEER4, PEER5, PEER6};

Whereas each element in this array is static uint8_t defined like this

static uint8_t PEER1[] {0x86, 0xF3, 0xEB, 0x7A, 0xE8, 0x3B};
static uint8_t PEER2[] {0x86, 0xF3, 0xEB, 0x7A, 0xA1, 0x09};
static uint8_t PEER3[] {0x84, 0x0D, 0x8E, 0x03, 0x95, 0xED};
static uint8_t PEER4[] {0x84, 0x0D, 0x8E, 0x03, 0x99, 0xD5};
static uint8_t PEER5[] {0x80, 0x7D, 0x3A, 0xC5, 0x2B, 0x79};
static uint8_t PEER6[] {0x84, 0x0D, 0x8E, 0x03, 0x95, 0x1D};

When I do


I get size:24. I am expecting the size to be 6. could someone explain ? I don't want to hardcode the total number of PEER in a separate integer variable. I want my for loop to run through each element till the total size of array.

    for (int i = 0; i < sizeof(neighbourSet); i++) {
         //do something for each PEER. 
  • uint8_t* is a pointer. on AVR it is 2 bytes. on 32bit architectures 4 bytes – Juraj Feb 2 '19 at 14:33
  • you want const uint8_t* const neighbourSet? – Juraj Feb 2 '19 at 14:39
  • 3
    Hint: sizeof() gives the number of bytes. You are looking for membersof(). It is often defined as #define membersof(x) (sizeof(x) / sizeof(x[0])). – Mikael Patel Feb 2 '19 at 15:07
  • int totalPeers = (sizeof(neighbourSet) / sizeof(neighbourSet[0])); worked. Thanks Mikael ! – Anum Sheraz Feb 2 '19 at 16:54
  • @MikaelPatel you should post that as an answer. I was going to post the same, but then I saw your comment. – RubberDuck Feb 3 '19 at 10:43

sizeof() gives the number of bytes. You are looking for membersof(). It is often defined as:

#define membersof(x) (sizeof(x) / sizeof(x[0]))

And in the example above:

for (int i = 0; i < membersof(neighbourSet); i++) {
     //do something for each PEER. 

For more practical C/C++ macro and type extensions please see the Cosa Types.h file.

| improve this answer | |
  • Sizeof doesn't work for pointers – SilvioCro Feb 4 '19 at 11:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.