0

I would like to calculate the number of element of the array using the following c code :

#include <stdio.h>

// Number of elements in an array
#define NUM_ELEM(x) (sizeof((x)) / sizeof((x)[0]))
#define LIST_KEY (char *[])
typedef struct dm_key_reg {
    char *obj;
    char **ukey;
}DMKEYREG;

DMKEYREG tab_reg_key[]={
{"Device_SS", LIST_KEY{"SerialSS", "SSS", "A"}},
{"Device__AP", LIST_KEY{"SerialAP", "III", "B"}},
{"Device___EP", LIST_KEY{ "SerialEP", "EEE", "CCC", "C"}},
{0}
};

int main(void)
{
    int i=0;
DMKEYREG *tab_key = tab_reg_key;
for (; tab_key->obj; tab_key++) {
    i++;
    printf("i=%d <>  ukeysize= %d\n",i, NUM_ELEM((tab_reg_key->ukey)));
}
}

but I got the following result:

i=1 <>  ukeysize= 1
i=2 <>  ukeysize= 1
i=3 <>  ukeysize= 1
Anis_Stack
  • 3,306
  • 4
  • 30
  • 53
  • Useful information here (A dup?): https://stackoverflow.com/questions/37538/how-do-i-determine-the-size-of-my-array-in-c – Damien Jan 04 '21 at 10:21
  • `ukey` is a dynamic array, what's preventing to have a separate variable to keep track of the count? – Inian Jan 04 '21 at 10:21
  • The information how many elements does `ukey` _points_ to is not stored anywhere. There is also no sentinel value. It's not possible to calculate it, the information is lost. – KamilCuk Jan 04 '21 at 10:24
  • As for the value `1`, you are effectively doing a ratio of the size of the pointer to itself, which will always be 1 – Inian Jan 04 '21 at 10:28
  • 2
    @Inian: When applied to a pointer, the expression is the size of the pointer divided by the size of the type it points to. This will not always be one. Note that the C standard permits different types of pointers to have different sizes. – Eric Postpischil Jan 04 '21 at 10:38

0 Answers0