3 ms·
One interesting usage of sizeof() is to calculate the dimension of an array at compile time: #define dim(x) (sizeof(x) / sizeof(x[0])) and this is handy
by pietrofmaggi 16y ago
One interesting usage of sizeof() is to calculate the dimension of an array at compile time:
#define dim(x) (sizeof(x) / sizeof(x[0]))
and this is handy for static arrays with dimension defined by its data, likes:
static const struct {
someEnum_t enCommand;
void (*Fxn)(stCommands_t *a_psCommand);
} m_stCmdMap[] = {
{CMD_SD_FREESPACE, _sdFreeSpace},
{CMD_SD_DISK_INFO, _sdDiskInfo},
{CMD_SD_FORMAT, _sdFormat},
}
When you add a new array elements, it just keep the stuffs going calculating it at any recompilation:
for (i=0; i<dim(m_stCmdMap); i++) {
if (m_stCmdMap[i].enCommand == stCmdLocal.enCommand) {
m_stCmdMap[i].Fxn(&stCmdCopy);
break;
}
}
Another useful macro to work with structs is offsetof(), its incredibly usefull when you have to port some code to different compilers/target with different alignments and paddings.