I have an array of animal names in the order that I intend to create each struct 'animal' and store it in farm_animals, a struct of animals.
typedef struct ani animal;
animal* farm_animals[128] = {0};
Although the below code is totally invalid, I have included it here to show exactly what I have thought of achieving in practice. I want to declare a variable of type animal corresponding to a string literal in the array, and then somehow use that literal as the name of the animal and store it in an array.
char* animal_names [] = {"Oliver", "Marcus", "Mike", "John", "Tom", "Daisy", "Lilac", "Rose", "Jim"};
for (int i = 0; i < 9; i ) {
animal animal_names[i];
farm_animals[i] = animal_names[i];
}
I have researched and found many other similar posts which conclude that since C is a compiled not interpreted language, it is not possible to name a variable with the value of a string. However, I was wondering if it is possible to concatenate the string name with a suffix (like the index number) to create an entirely new 'string name' to refer to the animal. I have also though of a macro using an array or the same animal_names
array, but this has not been clear for me to implement as a beginner.
I think this sort of idea in C is far-fetched, but I really wonder if there is a way to name these structs using a for loop and array of names, rather than manually creating 100 structs.
CodePudding user response:
Yes, it is not possible to dynamically name variables in C. If I understand correctly, you want to create an animal type corresponding to a string and then name it that name.
The advantage with using structs is that you can combine related/relevant data into a single variable (the struct) – which itself is a collection of multiple variables.
I would suggest organizing something like this:
typedef struct animal {
char[20] name;
char[20] type;
} animal;
You can replace the character array with a pointer to the string (char*
) as well. Also, if you know the type of animals that could be created you can instead create an enum like this:
#define MAX_NAME_LEN 20
#define MAX_NUM_ANIMALS 10
enum animalType {
LION,
ELEPHANT,
FALCON,
PARROT
};
typedef struct animal {
char[MAX_NAME_LEN] name;
enum animalType type;
} animal;
int main(void) {
animal listOfAnimals[MAX_NUM_ANIMALS];
listOfAnimals[0].type = PARROT;
listOfAnimals[0].name = "my parrot";
return 0;
}
So, instead of making 100 structs, you would make an array of structs and store the type of animal as a data member. Then you could use some mapping mechanism or conditional logic to assign these types to the struct variables as per your needs.