You could use arrays and macros:
struct book {
char name;
int page;
};
#ifndef __cplusplus
struct
#endif
book library[3];
#define b2 (library[0])
#define b3 (library[1])
#define b4 (library[2])
void initialize(void)
{
b2.name = 'a';
b2.page = 5;
b3.name = 'F';
b3.page = -85;
b4.name = '$';
b4.page = 65535;
}
void Print_Library(void)
{
unsigned int i = 0;
for (i = 0; i < 3; ++i)
{
printf("First character of book %d: %c\n", i, library[i].name);
printf("Page of book %d: %d\n", i, library.page);
printf("\n");
}
}
The name field is a single character not a string.
Note: I used the #if
preprocessor directive because instances of structures are defined differently between C and C++ and you specified both.
Edit 1: Accessing variables by name during run-time.
Although I have never needed to access variables by name during run-time, one method is to map variables to their names.
struct book; // forward declaration, see above.
struct Variable_Name_Entry
{
#ifdef __cplusplus // Required since you tagged both languages
std::string name;
book * p_variable;
#else
char name[16];
struct book * p_variable;
#endif
};
#ifndef __cplusplus
struct
#endif
Variable_Name_Entry variable_names[] =
{
{"b2", &b2},
{"b3", &b3},
{"b4", &b4},
};
const unsigned int number_of_variable_names =
sizeof(variable_names) / sizeof(variable_names[0]);
#ifndef __cplusplus
struct
#endif
book * name_to_variable(const char * p_name)
{
unsigned int i = 0;
for (i = 0; i < number_of_variable_names; ++i)
{
#ifdef __cplusplus
if (variable_names[i].name == p_name)
#else
if (strcmp(variable_names[i].name, p_name) == 0)
#endif
{
return variable_names[i].p_variable;
}
}
return NULL;
}
Do you really need to access variable by names or is there a different design available?