Re:Ask HN: An Advanced C Tutorial
by pietrofmaggi on Friday July 16, 2010 @03:58PM
(#1522333)
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.
One interesting use of sizeof i remember in my C++ project was to override new and delete operators where a void pointer is passed and sizeof is used to keep track of how much memory is allocated/deallocated.