I try to get the address of some struct member in array of structures but i don't want to use name of that member.
It should be something like this:
typedef struct{
unsigned char MrChar;
unsigned short MrShort;
unsigned long MrLong;
unsigned char MrArray[5];
}tModule;
static tModule taModulesArray[MODULES_AMOUNT] = { // MODULES_AMOUNT = 2
{0x22, 0x3298, 0x92324583, "djsoe"}, // Module 1
{0x33, 0x1843, 0x65644113, "gskwc"}, // Module 2
};
unsigned long usGetMemberAddr(unsigned long ulModule, unsigned long ulMember){
unsigned long Address;
Address = abs(taModulesArray_BaseAddress - taModulesArray[ulModule].[ulMember]);
return Address;
}
I need that for quick modification of configuration (in EEPROM) which is in different structs. So I try to do function which takes number of module and index of one of the module member and returns offset of for proper member.
If there is any possibility for something like that line before return?
You could do it by using a helper array, using
offsetof
:Note that your formula could be simplified as:
Or even further:
Note:
offsetof
is defined instddef.h
. See this Wikipedia article for more.If your compiler doesn't have this, one implementation of
offsetof
could be:We can use the below logic also to find the offset of each memebers of a structure and then we can directly add it to the base addres of the particular instance of the structure variable.