Caglayan Dokme
Caglayan Dokme

Reputation: 1217

How can I find the size of an initializer in C?

I'm trying to define a list which includes the MAC addresses of our devices. And I would like to do it with a macro. Here is a sample of the list I defined:

#define WHITELIST_DEVICE {                                  \
                      {0x45,0x11,0xDF,0xED,0x2B,0x61},  \
                      {0xAB,0x11,0xDF,0x61,0x6B,0x2B},  \
                      {0x61,0x6B,0x3B,0xED,0x61,0x61},  \
                      {0xDF,0x55,0xDF,0x6B,0x6B,0x61},  \
                     } /**< List of device mac addresses in whitelist*/

After defining the list, I would like to gather its size like columns and rows. What is the easiest way to do that? You can also suggest me a new way to define the list. The code will work on an Embedded System. So, it shouldn't have heavy algorithms :)

Upvotes: 2

Views: 149

Answers (1)

Assuming there are always six columns, you can do the calculation by using the above initializer in a compound literal.

#define WHITELIST_DEVICE_LENGTH ( sizeof ((int[][6])WHITELIST_DEVICE) / sizeof ((int[][6])WHITELIST_DEVICE[0]) ) 

or

#define WHITELIST_DEVICE_LENGTH ( sizeof ((int[][6])WHITELIST_DEVICE) / sizeof (int[6]) /* a "row" */ ) 

(int[][6])WHITELIST_DEVICE - Would normally creates an anonymous object in the scope it appears in. But when the literal is an operand to sizeof (expression variant) it will not create any object, instead only doing calculation on the types in question during compilation.

The sizeof trick for getting an array size needs no explaining I hope. It also makes the choice of int as array element immaterial, since that size will be canceled out during division. I chose that type to avoid any potential issues with your literal numbers not fitting in the array elements.

Upvotes: 6

Related Questions